leetcode 222. Count Complete Tree Nodes

来源:互联网 发布:软件维护工程师 编辑:程序博客网 时间:2024/06/04 21:12
# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def countNodes(self, root):        """        :type root: TreeNode        :rtype: int        """        if not root:            return 0        l = root        r = root        LeftLength = 0        RightLength = 0        while l is not None:            l = l.left            LeftLength += 1        while r is not None:            r = r.right            RightLength += 1        if LeftLength == RightLength:            return 2 ** LeftLength - 1        else:            return 1+self.countNodes(root.left)+self.countNodes(root.right)