LeetCode | 0222. 完全二叉树的节点个数【Python】

Problem

LeetCode

Given a complete binary tree, count the number of nodes.

Note:

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2^h nodes inclusive at the last level h.

Example:

Input: 
    1
   / \
  2   3
 / \  /
4  5 6

Output: 6

问题

力扣

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

说明:

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

示例:

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

输出: 6

思路

中序遍历

普通二叉树:遍历一遍左右子树
满二叉树:节点总数与高度呈指数关系
完全二叉树:结合普通二叉树与满二叉树

时间复杂度

时间复杂度是 O(logN*logN)

因为一棵完全二叉树中,必存在一棵子树是满二叉树。因此,肯定会触发 heightleft == heightright 条件,所以递归深度就是树的高度,时间复杂度是 O(logN)。每次递归就是 while 循环,时间复杂度也是 O(logN),总体时间复杂度就是 O(logN*logN)。

Python3 代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        l = TreeNode(None)
        l = root
        r = TreeNode(None)
        r = root
        heightleft, heightright = 0, 0  # 记录左右子树的高度
        while l != None:
            l = l.left
            heightleft += 1
        while r != None:
            r = r.right
            heightright += 1
        
        # 如果左右子树高度相同,则是一棵满二叉树
        if heightleft == heightright:
            return 2**heightleft - 1
        
        # 如果左右子树高度不相同,则是按普通二叉树计算
        return 1 + self.countNodes(root.left) + self.countNodes(root.right)

GitHub 链接

Python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wonz

创作不易,一块就行。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值