Given a complete binary tree, count the number of nodes.
思路:
找到最左边的节点和最右边的节点,如果二者高度一致,那么说明最后一层是满的,返回2^h-1。否则,递归下去。
代码:
int countNodes(TreeNode* root) {
if(!root) return 0;
int hl=0, hr=0;
TreeNode *l=root, *r=root;
while(l) {hl++;l=l->left;}
while(r) {hr++;r=r->right;}
if(hl==hr) return pow(2,hl)-1;
return 1+countNodes(root->left)+countNodes(root->right);
}