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

暴力法:

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if not root:
            return 0
        else:
            return 1+self.countNodes(root.left)+self.countNodes(root.right)
执行用时 :92 ms, 在所有 python3 提交中击败了85.10%的用户
内存消耗 :21.6 MB, 在所有 python3 提交中击败了5.26%的用户
 
 
运用完全二叉树的性质:
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)
执行用时 :80 ms, 在所有 python3 提交中击败了98.16%的用户
内存消耗 :21.3 MB, 在所有 python3 提交中击败了5.26%的用户
 
——2019.11.19
posted @ 2019-11-19 15:48  欣姐姐  阅读(168)  评论(0编辑  收藏  举报