0%

Leetcode222-countCompleteTreeNodes

Description

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

Note:

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.

Example

1
2
3
4
5
6
7
8
Input: 
1
/ \
2 3
/ \ /
4 5 6

Output: 6

Solution

Method 1: O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
return countNodes(root.left) + countNodes(root.right) + 1;
}
}

Method 2: $O(log^2(n))$

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
class Solution{
public int countNodes(TreeNode root) {
int left = leftHeight(root);
int right = rightHeight(root);

if (left == right)
return (1 << left) - 1;
else return countNodes(root.left) + countNodes(root.right) + 1;
}
private int leftHeight(TreeNode node){
int dep = 0;
while(node != null){
node = node.left;
dep++;
}
return dep;
}
private int rightHeight(TreeNode node){
int dep = 0;
while(node != null){
node = node.right;
dep++;
}
return dep;
}
}