文章目录
  1. 1. Count Complete Tree Nodes
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题

Count Complete Tree Nodes

题目

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

思路

根据完全二叉树的性质,左子树和右子树必存在一个满树。如何判断满树,满树的结点如何计算。

解题

c++版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

class Solution {
public:
int countNodes(TreeNode* root) {
if(!root)
return 0;
TreeNode *left=root->left;
TreeNode *right=root->right;
int ldepth=1;
int rdepth=1;
while(left){
ldepth++;
left=left->left;
}
while(right){
rdepth++;
right=right->right;
}
if(ldepth==rdepth)
return pow(2,ldepth)-1;
else
return countNodes(root->left)+countNodes(root->right)+1;

}
};

python版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
# @param {TreeNode} root
# @return {integer}
def countNodes(self, root):
if not root:
return 0
lt=root
rt=root
ldepth=0
rdepth=0
while lt:
ldepth+=1
lt=lt.left
while rt:
rdepth+=1
rt=rt.right
if ldepth==rdepth:
return 2**ldepth-1
else:
return self.countNodes(root.left)+self.countNodes(root.right)+1

文章目录
  1. 1. Count Complete Tree Nodes
    1. 1.1. 题目
    2. 1.2. 思路
    3. 1.3. 解题