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

题目描述:

 方法一: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)

猜你喜欢

转载自www.cnblogs.com/oldby/p/11622557.html