Topic:
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 2hnodes inclusive at the last level H.
Ideas:
Full v.s. Complete Binary Trees
According to Wikipedia
- A full binary tree (sometimes proper binary tree or 2-tree) are a tree in which every node other than the leaves have both ch Ildren.
- A complete binary tree was a binary tree in which every level, except possibly the last, was completely filled, and all node S is as far as possible.
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
Time complexity is O (h^2).
Code:
1 Public intcountnodes (TreeNode root) {2 if(root==NULL)3 return0;4 5 intleft = Getleftheight (root) +1; 6 intright = Getrightheight (root) +1;7 8 if(left==Right ) {9 return(2<< (Left-1))-1;Ten}Else{ One returnCountnodes (Root.left) +countnodes (root.right) +1; A } - } - the Public intGetleftheight (TreeNode N) { - if(n==NULL)return0; - - intHeight=0; + while(n.left!=NULL){ -height++; +n =N.left; A } at returnheight; - } - - Public intGetrightheight (TreeNode N) { - if(n==NULL)return0; - in intHeight=0; - while(n.right!=NULL){ toheight++; +n =N.right; - } the returnheight; *}
reference:http://www.programcreek.com/2014/06/leetcode-count-complete-tree-nodes-java/
*count Complete Tree Nodes