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.
The direct traversal will time out and the code is as follows:
1 classSolution {2 Public:3 intCountnodes (treenode*root) {4 intCount =0;5Queue<treenode *>temp;6 if(Root = =NULL)7 {8 return 0;9 }Ten Temp.push (root); One while(!temp.empty ()) A { -TreeNode * Node =Temp.front (); -count++; the Temp.pop (); - - if(Node->left! =NULL) - { +Temp.push (node->Left ); - } + if(Node->right! =NULL) A { atTemp.push (node->Right ); - } - } - returncount; - } -};This problem to find the total number of nodes of the binary tree, so for a node, if the number of left subtree traversal and the number of right sub-tree traversal is equal, it is full of two fork tree, then the formula is 2^h-1, if not equal is not full two fork tree, recursive calculation Saozi right subtree plus the current node can be. The code is as follows:
1 classSolution {2 Public:3 intCountnodes (treenode*root) {4 intLeftnum =0;5 intRightnum =0;6TreeNode * ptr =Root;7 8 if(Root = =NULL)9 {Ten return 0; One } A - while(1) - { thePTR = ptr->Left ; - if(PTR! =NULL) - { -++Leftnum; + } - Else + { A Break; at } - } -PTR =Root; - while(1) - { -PTR = ptr->Right ; in if(PTR! =NULL) - { to++Rightnum; + } - Else the { * Break; $ }Panax Notoginseng } - if(Leftnum = =0&& Rightnum = =0) the { + return 1; A } the if(Leftnum = =rightnum) + { - returnPow2, Leftnum +1) -1; $ } $ return 1+ countnodes (root->left) + countnodes (root->Right ); - } -};
222. Count Complete Tree Nodes