leetcode----222. Count Complete Tree Nodes

链接:

https://leetcode.com/problems/count-complete-tree-nodes/

大意:

给定一棵完全二叉树,求二叉树的节点数。例子:

思路:

任意一种遍历方法都可以解决。

代码:

class Solution {
    // 以任意一种遍历方法得到节点数
    private int count = 0;
    public int countNodes(TreeNode root) {
        preOrder(root);
        return count;
    }
    public void preOrder(TreeNode root) {
        if (root == null)
            return ;
        count++;
        preOrder(root.left);
        preOrder(root.right);
    }
}

结果:

结论:

这种解法是对于任何树都适用的。对于完全二叉树,根据其不同于一般树的性质,应该是有另外更高效的解法的。(不过这种“不太高效”的方法也能打败100%,应该是测试用例太少了。。。) 

改进:

通过完全二叉树不同于一般二叉树的特性,可以计算出树的高度h以及最后一层的节点数order,然后返回 order + 2 ^ (h - 1) - 1即可。

class Solution {
    private int order = -1; // 记录最后一个节点在其所在层的序号
    public int countNodes(TreeNode root) {
        int h = getHeight(root);
        if (h == 0)
            return 0;
        getCountLastLayer(root, 1, h, 1);
        return order + (1 << (h - 1)) - 1;
    }
    // 获得树的高度
    public int getHeight(TreeNode root) {
        if (root == null)
            return 0;
        return 1 + getHeight(root.left);
    }
    // 获得最后一个节点在其所在层的序号(即可知最后一层有多少个节点) num为当前节点在所在层的序号
    public void getCountLastLayer(TreeNode root, int num, int h, int currLayer) {
        if (currLayer == h) {
            order = num;
            return ;
        }
        if (root.right != null)
            getCountLastLayer(root.right, num * 2, h, currLayer + 1);
        if (order != -1) // 找到最后一个节点 直接return
            return ;
        if (root.left != null)
            getCountLastLayer(root.left, num * 2 - 1, h, currLayer + 1);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值