首页 > 其他 > 详细

[leetcode]Count Complete Tree Nodes

时间:2020-02-09 00:44:28      阅读:69      评论:0      收藏:0      [点我收藏+]

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

# 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

    

  

[leetcode]Count Complete Tree Nodes

原文:https://www.cnblogs.com/lautsie/p/12285633.html

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