【LeetCode222】完全二叉树的节点个数

题目描述

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

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

思路与算法

  1. base cases:
    • 空树:节点的数量是 0
    • 完美二叉树:2^d−1
  2. 递归步骤
    • 递归计算左子树中的节点数
    • 递归计算右子树中的节点数
    • 为当前根节点加 1
  3. 结果组合

代码

python3 复制代码
# 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 countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0

        left_depth = self.getLeftDepth(root)
        right_depth = self.getRightDepth(root)
        if left_depth == right_depth:
            return (1 << left_depth) - 1 # same as 2^left_depth - 1

        return 1 + self.countNodes(root.left) + self.countNodes(root.right)

    def getLeftDepth(self, node: TreeNode) -> int:
        depth = 0
        while node:
            depth += 1
            node = node.left
        return depth
    
    def getRightDepth(self, node: TreeNode) -> int:
        depth = 0
        while node:
            depth += 1
            node = node.right
        return depth
        

总结

相关推荐
forest_091 天前
《AI 编程 Harness 实战手册》04|审批这道门:点了一百次“允许”,还剩多少作用?
人工智能·算法·prompt·agi
H.莓飛1 天前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
不会武功不懂江湖1 天前
RISC-V链接器与链接脚本
汇编·算法·risc-v
Zwawa1 天前
卡尔曼到底在算什么:从一维到它的变式以及工程版卡尔曼滤波算法C语言实现
c语言·算法·嵌入式
电科_银尘1 天前
【大模型算法与工程 14】Tokenizer与Embedding:文本如何变成模型输入
算法·embedding
饮水桶_T1 天前
Python 面向对象(十七)|继承、封装、多态 笔记
数据结构·笔记·算法
文丑颜不良啊1 天前
LeetCode3281~3300题目解析
java·leetcode
地平线开发者1 天前
让 AI Agent 和 征程6 台架高效、稳定、安全地协作
算法·安全·自动驾驶
kyle~1 天前
SHA-256 哈希去重
算法·哈希算法