zoukankan      html  css  js  c++  java
  • 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
    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    每日日报
    设计模式分类及典型实现
    SpringBean的生命周期
    Nginx
    大话--单例模式
    类图--小总结
    设计模式原则概述
    大话--装饰者模式
    Redis基础
    SpringIOC的实现原理
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11889996.html
Copyright © 2011-2022 走看看