leedcode-完全二叉树的节点个数

自己写的,使用广度优先BFS,迭代:

复制代码
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        # 如果根节点为空,则树中节点数为 0
        if not root:
            return 0
        
        # 初始化队列,并将根节点放入队列中
        queue = [root]
        # 计数器,初始值为 1,因为根节点已经算作一个节点了
        count = 1
        
        # 遍历队列,直到队列为空
        while queue:
            # 弹出队列中的第一个节点
            cur = queue.pop(0)
            # 如果当前节点有左子节点,将左子节点加入队列,并将计数器加一
            if cur.left:
                queue.append(cur.left)
                count += 1
            # 如果当前节点有右子节点,将右子节点加入队列,并将计数器加一
            if cur.right:
                queue.append(cur.right)
                count += 1
        
        # 返回计数器的值,即树中节点的总数
        return count
复制代码

 利用完全二叉树的特性实现:

复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    # 求二叉树的深度
    def height(self, root:TreeNode):
        height = 0
        while root:
            root = root.left
            height += 1

        return height

    def countNodes(self, root: TreeNode) -> int:
        # 空树,节点数为 0
        if root == None:
            return 0
        # 求左子树和右子树的深度
        leftHeight = self.height(root.left)
        rightHeight = self.height(root.right)
        
        # 如果左子树的深度 = 右子树的深度,左子树为满二叉树
        # 节点数 = 左子树的深度 + 右子树的深度 + 根节点
        if leftHeight == rightHeight:
            return (2 ** leftHeight - 1) + self.countNodes(root.right) + 1
        # 如果左子树的深度 > 右子树的深度,右子树为满二叉树
        # 节点数 = 左子树的深度 + 右子树的深度 + 根节点
        else:
            return (2 ** rightHeight - 1) + self.countNodes(root.left) + 1
复制代码

 纯递归:

复制代码
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        # 如果根节点为空,则返回 0
        if not root:
            return 0
        
        # 递归计算左子树的节点数
        leftcount = self.countNodes(root.left)
        
        # 递归计算右子树的节点数
        rightcount = self.countNodes(root.right)
        
        # 返回左右子树节点数之和加上根节点,即整棵树的节点数
        return leftcount + rightcount + 1
复制代码

 

posted @   Junior_bond  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示