首页 > 其他 > 详细

222 Count Complete Tree Nodes

时间:2015-07-07 07:00:51      阅读:224      评论:0      收藏:0      [点我收藏+]

1,这道题如果纯用递归数点而不利用其为一个complete binary tree的话会超时。

2.为了利用这个条件,比较左右两子数的高度:1, 如果相等则左子树为完全二叉树 2, 如果不等, 则右子树为完全二叉树。

3,完全二叉树的node个数为pow(2,depth)-1, 因此可以不用递归数点节约时间。

4,因为是complete binary tree,子树的深度只用一直找寻左儿子即可得到深度

总体复杂度O(lgn * lgn)

class Solution:
    # @param {TreeNode} root
    # @return {integer}
    def countNodes(self, root):
        if not root:
            return 0
        leftDepth = self.getDepth(root.left)
        rightDepth = self.getDepth(root.right)
        if leftDepth == rightDepth:
            return pow(2, leftDepth) + self.countNodes(root.right)
        else:
            return pow(2, rightDepth) + self.countNodes(root.left)

    def getDepth(self, root):
        if not root:
            return 0
        return 1 + self.getDepth(root.left)

 

222 Count Complete Tree Nodes

原文:http://www.cnblogs.com/dapanshe/p/4625853.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!