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.
Test instructions: Find the number of nodes for a fully binary tree.
Idea: To find the last layer of the last node, you can judge the left and right nodes the most of the number of layers is the same, if the same, then the left subtree is full of two fork tree, if different, the tree is full two.
In the process of solving, it is necessary to use the power of the operation, if the use of Math.pow will time out, you can consider a bit operation, but to consider 2 of the 0 power of the special case.
Code:
Public classSolution { Public intcountnodes (TreeNode root) {if(Root = =NULL) return0; intleft =Countlevel (Root.left); intright =Countlevel (root.right); intLeftpow = 2<< (left-1); intRightpow = 2<< (right-1); if(left = = 0)//0 Power,<< not come outLeftpow = 1; if(right = = 0) Rightpow= 1; if(left = =Right ) { returnLeftpow +countnodes (root.right); }Else returnRightpow +countnodes (Root.left); } Public intcountlevel (TreeNode root) {if(Root = =NULL) return0; intCount = 0; while(Root! =NULL) {Count++; Root=Root.left; } returncount; }}
[Leetcode-java] Count Complete Tree Nodes