zoukankan      html  css  js  c++  java
  • [LeetCode] 完全二叉树的节点个数

    题目链接: https://leetcode-cn.com/problems/count-complete-tree-nodes

    难度:中等

    通过率:57.4%

    题目描述:

    给出一个 完全二叉树 ,求出该树的节点个数。

    说明:

    完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第h 层,则该层包含 1~ 2h 个节点。

    示例:

    输入:
        1
       / 
      2   3
     /   /
    4  5 6
    
    输出: 6
    

    思路:

    暴力,每个节点都访问一下,看有多少个

    时间复杂度:(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)
    

    这样不是完全二叉树也可以计算,但是没有用到完全二叉树的性质!

    我们可以通过运用性质,完全二叉树的节点个数等于 (2^{h} - 1)

    所以有,时间复杂度:(O(log(n)^2))

    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)
    
  • 相关阅读:
    备用
    Python进阶
    *args 和 **kwargs
    C语言
    【Pythno库】-Re
    【C语言】-struct
    Django By Example
    字符串
    Python库
    【Keil】Keil5-改变字的大小和颜色
  • 原文地址:https://www.cnblogs.com/powercai/p/11431934.html
Copyright © 2011-2022 走看看