给定一棵完全二叉树(最后一层所有节点都在最左侧,其余所有层节点数都为2^h),求其节点数。
最简单的方法就是遍历一遍,把节点数加起来,但时间复杂度太高。
以最左边的路径长作为二叉树的高度,对于一个节点,如果左子树高度和右子树高度一样,说明左子树为满二叉树,此时把其左子树的节点数计算出来,加入总数,对右子树递归计算;如果左子树和右子树不一样高,说明左子树不是满二叉树,而右子树是满二叉树(高度不一样),此时把右子树的节点数算出来加入总数,对左子树进行递归计算。直到只有一个节点时,总数再加1.
class Solution {
int num = 0;
int height(TreeNode root) { //计算最左路径高度
if(root == null)
return 0;
int h = 0;
TreeNode node = root;
while(node != null){
h++;
node = node.left;
}
return h;
}
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
if(root.left == null && root.right == null){ //到达叶子节点
num += 1;
return num;
}
int h = height(root.left);
if(h == height(root.right)){ //左右子树一样高,左子树为满二叉树
num += 1 << h;
countNodes(root.right);
}
else{ //左右子树不一样高,右子树为h-1层的满二叉树,左子树不是满二叉树
num += 1 << (h - 1);
countNodes(root.left);
}
return num;
}
}
大神的代码:
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
int num=1;
TreeNode *curR(root->left), *curL(root->left);
while(curR) // curR is the rightmost edge, which has a height equal to or less than the leftmost edge
{
curL = curL->left;
curR = curR->right;
num = num<<1;
}
return num + ( (!curL)?countNodes(root->right):countNodes(root->left) );
}
};