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);
}
本文介绍了一种计算完全二叉树中节点数量的方法。通过查找最左节点和最右节点的高度,判断是否为满树,并递归计算节点总数。

被折叠的 条评论
为什么被折叠?



