美文网首页
222. Count Complete Tree Nodes

222. Count Complete Tree Nodes

作者: 阿团相信梦想都能实现 | 来源:发表于2016-12-17 06:35 被阅读0次
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def height(self,root):
        return 0 if root==None else 1+self.height(root.left)
        
    def countNodes(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        h=self.height(root)
        if h<=0:return 0
        elif self.height(root.right)==h-1:
            return 2**(h-1)+self.countNodes(root.right)
        else:
            return 2**(h-2)+self.countNodes(root.left)
                

相关文章

网友评论

      本文标题:222. Count Complete Tree Nodes

      本文链接:https://www.haomeiwen.com/subject/vyeomttx.html