Count Complete Tree Nodes in C++


Suppose we have a complete binary tree, we have to count the number of nodes. So if the tree is like −

So the output will be 6.

To solve this, we will follow these steps −

  • This will use the recursive approach. This method, countNodes() is taking the root as argument.

  • hr := 0 and hl := 0

  • create two nodes l and r as root

  • while l is not empty

    • increase hl by 1

    • l := left of l

  • while r is not empty

    • r := right of r

    • increase hr by 1

  • if hl = hr, then return (2 ^ hl) – 1

  • return 1 + countNodes(left of root) + countNodes(right of root)

Let us see the following implementation to get better understanding −

Eample

class Solution {
   public:
   int fastPow(int base, int power){
      int res = 1;
      while(power > 0){
         if(power & 1) res *= base;
         base *= base;
         power >>= 1;
      }
      return res;
   }
   int countNodes(TreeNode* root) {
      int hr = 0;
      int hl = 0;
      TreeNode* l = root;
      TreeNode* r = root;
      while(l){
         hl++;
         l = l->left;
      }
      while(r){
         r = r->right;
         hr++;
      }
      if(hl == hr) return fastPow(2, hl) - 1;
      return 1 + countNodes(root->left) + countNodes(root->right);
   }
};

Input

[1,2,3,4,5,6,7,8,9,10]

Output

10
raja
Published on 05-Feb-2020 10:11:42
Advertisements