菜鸟刷题之路——Q31:完全二叉树的节点个数

问题 :222. 完全二叉树的节点个数

给出一个完全二叉树,求出该树的节点个数。

说明:

完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

分析

分析:利用完全二叉树的特点进行加速,一种是剪枝的方式,一种的二分的方式。二分的方式代码优美而且好理解,这里我是直接copy了LeetCode评论区的大佬的解法

Code

// 二分
class Solution {
    public int countNodes(TreeNode root) {
        /**
        完全二叉树的高度可以直接通过不断地访问左子树就可以获取
        判断左右子树的高度: 
        如果相等说明左子树是满二叉树, 然后进一步判断右子树的节点数(最后一层最后出现的节点必然在右子树中)
        如果不等说明右子树是深度小于左子树的满二叉树, 然后进一步判断左子树的节点数(最后一层最后出现的节点必然在左子树中)
        **/
        if (root==null) return 0;
        int ld = getDepth(root.left);
        int rd = getDepth(root.right);
        if(ld == rd) return (1 << ld) + countNodes(root.right); // 1(根节点) + (1 << ld)-1(左完全左子树节点数) + 右子树节点数量
        else return (1 << rd) + countNodes(root.left);  // 1(根节点) + (1 << rd)-1(右完全右子树节点数) + 左子树节点数量
        
    }

    private int getDepth(TreeNode r) {
        int depth = 0;
        while(r != null) {
            depth++;
            r = r.left;
        }
        return depth;
    }
    
// 剪枝方法
class Solution {
/*
执行结果:
通过
显示详情
执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:40.5 MB, 在所有 Java 提交中击败了98.37% 的用户
*/
    int curHeight = 0, lackNode = 0, flag = 0;
    public int countNodes(TreeNode root) {
        if (root == null) return 0;
        TreeNode temp = root;
        int height = 0;
        // 获得高度
        while (temp != null) {
            height++;
            temp = temp.left;
        }
        travel(root,height);
        return (1 << height) -1 - lackNode;
    }
    public int travel(TreeNode root,int height) {
        if (flag == 1 || root == null) return 1;
        curHeight++;
        // 倒数第二层节点
        if (curHeight == height-1) {
            if (root.left == null) lackNode += 2;
            else if (root.right == null) lackNode += 1;
            if (root.right != null || root.left != null) {
                // 结束递归
                flag = 1;
                return 1;
            }
        } else {
            // 不访问叶子节点
            travel(root.right,height);
            travel(root.left,height);
        }
        curHeight--;
        return 0;       
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值