二叉树:完全二叉树的节点数

    给定一棵完全二叉树(最后一层所有节点都在最左侧,其余所有层节点数都为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) );
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值