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.
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { Public intcountnodes (TreeNode root) {//suitable for any two-fork tree /*method One: if (root==null) return 0; Return Countnodes (Root.left) +countnodes (root.right) +1;*/ /*Method Two: if (root==null) return 0; Linkedlist<treenode> queue=new linkedlist<treenode> (); Queue.add (root); int count=0; while (!queue.isempty ()) {int temp=queue.size (); Count+=temp; for (int i=0;i<temp;i++) {TreeNode node=queue.remove (); if (node.left!=null) {queue.add (node.left); count++; } if (Node.right!=null) {queue.add (node.right); count++; }}} return count;*/ /*can prove that a complete binary tree at least one of the subtree is full of two fork trees. The number of nodes with a two-forked tree is 2^k-1,k is the depth of the tree. So we can first determine whether the tree is full of two forks, then the result is returned directly, if it is not to solve the subtree recursively. This does not have to traverse all nodes. The complexity is less than O (N), which is smaller than the complexity of all point traversal, and the best case is O (LgN). The projections are probably between O (LgN) ~o (N). */ if(root==NULL)return0; TreeNode L=Root; TreeNode R=Root; intLefth=0; intRighth=0; while(l!=NULL) {L=L.left; Lefth++; } while(r!=NULL) {R=R.right; Righth++; } if(lefth==righth) { return(1<<lefth)-1;//Note the priority level}Else{ returnCountnodes (Root.left) +countnodes (root.right) +1; } }}
[Leedcode 222] Count Complete Tree Nodes