Question:
Count Complete Tree NodesTotal accepted:11040 Total submissions:53992my submissions QuestionSolution
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, was completely filled, and all nodes As far left as possible. It can has between 1 and 2h nodes inclusive at the last level H.
Analysis:
Steps to solve this problem:
1) Get the height of Left-most part
2) Get the height of Right-most part
3) When they is equal, the # of nodes = 2^h-1
4) when they is not equal, recursively get # of nodes from Left&right sub-trees
Public intCountnodes (TreeNode root) {//Notice The traditional traversal would exceed the time limit and we also can ' t use Math.pow () cause it is too slow. if(Root = =NULL)return0; TreeNode LN= root, RN =Root; intL = 0, r = 0; while(LN! =NULL) {L++; ln=Ln.left; } while(rn! =NULL) {R++; RN=Rn.right; }//Math.pow (2,n) = 2<< (n-1) e.g. 2^1 = = 2 = 2<<0 if(L = = r)return(2<< (L-1))-1;//notice "<<" is right connect so we need "() out of 2<< (L-1)" return1 + countnodes (root.left) +countnodes (root.right); }
8.8 Leetcode 222 Count complete Tree Nodes