[leetcode]Count Complete Tree Nodes

如果完全二叉树,最左和最右的路径是一样长的。利用这个递归。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        leftHeight = self.countLeftHeight(root)
        rightHeight = self.countRightHeight(root)
        if leftHeight == rightHeight:
            return 2 ** leftHeight - 1
        else:
            return 1 + self.countNodes(root.left) + self.countNodes(root.right)

    def countLeftHeight(self, root: TreeNode) -> int:
        height = 0
        while root is not None:
            height += 1
            root = root.left
        return height

    def countRightHeight(self, root: TreeNode) -> int:
        height = 0
        while root is not None:
            height += 1
            root = root.right
        return height

    

  

posted @ 2020-02-08 23:15  阿牧遥  阅读(121)  评论(0编辑  收藏  举报