码迷,mamicode.com
首页 > 其他好文 > 详细

222.Count Complete Tree Nodes

时间:2016-06-13 11:38:39      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

    /*
     * 222.Count Complete Tree Nodes 
     * 11.20 By Mingyang
     * 最先各自计算最左边那一束到底的长度,再计算右边到底的长度,如果相等,ok,# of nodes = 2^h -1(计算满树很简单的!)
     * 若不相等,再继续迭代,这样做节省了很多时间
     * T(n)=logn+2T(n/2),最后算出来就是n,其实可以这么理解,每个节点都只是访问了一次,所以还是n。注意树的高度是logn
     * 这个题目设定的就是让你先判断是否为完全树,然后其余的都是一样的
     */
    public int countNodes(TreeNode root) {
        if (root == null)
            return 0;
        int leftHeight = 1, rightHeight = 1;
        // 计算左子树
        TreeNode temp = root.left;
        while (temp != null) {
            temp = temp.left;
            leftHeight++;
        }
        // 计算右子树
        temp = root.right;
        while (temp != null) {
            temp = temp.right;
            rightHeight++;
        }
        if (leftHeight == rightHeight)
            return (1 << leftHeight) - 1;
        // 也可以:(2<<(left-1))-1,这里h是left-1
        return countNodes(root.left) + countNodes(root.right) + 1;
    }

 

222.Count Complete Tree Nodes

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5579655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!