Complete binary tree: The nodes of each row except the last row have two sons, and the last row of nodes is left as far as possible.
VER0:
1 class Solution {2public:3 int countnodes (treenode* root) {4 ifreturn0 ; 5 return 1 + countnodes (root->left) + countnodes (root-> right); 6 }7 };
Not surprisingly, tle.
Ver1:
1 classSolution {2 Public:3 intCountnodes (treenode*root) {4 if(!root)return 0;5treenode* L = root, * r =Root;6 intLlen =0, Rlen =0;7 //While (l->left) {//error! Correct:while (L)8 //++llen;9 //L = l->left;Ten // } One //While (r->right) { A //++rlen; - //r = r->right; - // } the for(; l!=null; ++llen, l=l->Left ); attention! - for(; r!=null; ++rlen, r=r->Right ); - returnLlen = = Rlen? (1<<llen)-1:1+ countnodes (root->left) + countnodes (root->Right );//attention - + - } +};
According to the last line of the node as far as possible on the left this feature, first calculate root->left->left-> This path is long and root->right->right-> This is a long path. If they are equal, the whole tree is full, using the geometric series formula (note that bit arithmetic is used), and the unequal is recursive.
Leetcode 222. Count Complete Tree Nodes