首页 > 其他 > 详细

leetcode-222-完全二叉树的节点个数

时间:2019-10-04 17:57:14      阅读:90      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

 

 方法一:O(N)

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if not root:
            return 0
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)

方法二:利用完全二叉树的性质

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if not root:
            return 0
        left_height = 0
        left_node = root
        right_height = 0
        right_node = root
        while left_node:
            left_node = left_node.left
            left_height += 1
        while right_node:
            right_node = right_node.right
            right_height += 1
        if left_height == right_height:
            return pow(2,left_height) - 1
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)

 

leetcode-222-完全二叉树的节点个数

原文:https://www.cnblogs.com/oldby/p/11622557.html

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