[ITint5] Count Number of Nodes in a Complete Binary Tree

http://www.itint5.com/oj/#4

In a complete binary tree every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

How can we count the total number of nodes in a complete binary tree?

A straightforward method is to traverse the tree, which takes O(n) in time, where n is the number of nodes. However, this method does not utilize the property of complete binary tree.

Since we know the tree is complete, it is very easy to find the height of the tree; the tricky part is how can we find the number of nodes in the last level.

We can utilize a binary search method to figure out how many nodes are in the last level. For each node, we check the "left height" of its left subtree and its right subtree, respectively. "Left height" means the depth of the leftmost leaf node. If the "left heights" are the same, we know that the left subtree is full; if the "left heights" are not the same, we know that the right subtree is full. By using recursion, we can easily obtain the result.

The complexity is O(log n * log n). We need log n iterations since the last level has at most n/2 nodes. For each iteration, we need to go to the leftmost, which takes at most O(log n).

 

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 8 Object-Oriented Design