⏰ Time complexity: O(h^2) = O(log n)^2, because at each level we are checking the left and right height again and again.
🧺 Space complexity: O(h), assuming recursion stack
Method 3 - Without Using Separate Height Method 🏆#
It first walks all the way left and right to determine the height and whether it’s a full tree, meaning the last row is full. If so, then the answer is just 2^height-1. And since always at least one of the two recursive calls is such a full tree, at least one of the two calls immediately stops. Again we have runtime O(log(n)^2).
publicintcountNodes(TreeNode root) {
if (root ==null)
return 0;
TreeNode left = root, right = root;
int height = 0;
// if right is null, left may still exist as it is complete BTwhile (right !=null) {
left = left.left;
right = right.right;
height++;
}
if (left ==null) {
return (1 << height) - 1;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}
left = root (root value 1)right = root (root value 1)
Find the height of right side:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Iteration 1=>left = root.left(node value 2)right = root.right(node value 3)height++=>1Iteration 2=>left = root.left(node value 4)right = root.right(node value 7)height++=>2Iteration 3=>left = root.left(node value 8)right = root.right(node value 15)height++=>3Iteration 4=>left = root.left(node value 16)right = root.right(node value null)height++=>4
Iteration 1=>left = root.left(node value 4)right = root.right(node value 5)height++=>1Iteration 2=>left = root.left(node value 8)right = root.right(node value 11)height++=>2Iteration 3=>left = root.left(node value 16)right = root.right(node value null)height++=>3
As again, tree is not perfect tree (left != null), we recurse.
Iteration 1=>left = root.left(node value 8)right = root.right(node value 9)height++=>1Iteration 2=>left = root.left(node value 16)right = root.right(node value null)height++=>2
As again, tree is not perfect tree (left != null), we recurse.