Algorithms first
完全二叉树的节点个数 · 交互式算法学习
高效统计完全二叉树节点数。
#222 · 二叉树
完全二叉树的节点个数
Count Complete Tree Nodes
root = [1,2,3,4,5,6]树 / 图3 个关键状态
步骤 1根左右极端高度不同。
lh=3,rh=2推荐
比较左右高度
时间
O(log² n)空间 O(log n)左右最深高度相等则是满二叉树,可用 2^h−1 直接计算。
1function countNodes(root) {2 if (!root) return 0;3 let l = root,4 r = root,5 lh = 0,6 rh = 0;7 while (l) {8 lh++;9 l = l.left10 }11 while (r) {12 rh++;13 r = r.right14 }15 return lh === rh ? 2 ** lh - 1 : 1 + countNodes(root.left) + countNodes(root.right);16}多语言参考
来源 · CC BY-SA 4.0 ↗Java · C++ · Go
这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。
1/**2 * Definition for a binary tree node.3 * public class TreeNode {4 * int val;5 * TreeNode left;6 * TreeNode right;7 * TreeNode() {}8 * TreeNode(int val) { this.val = val; }9 * TreeNode(int val, TreeNode left, TreeNode right) {10 * this.val = val;11 * this.left = left;12 * this.right = right;13 * }14 * }15 */16class Solution {17 public int countNodes(TreeNode root) {18 if (root == null) {19 return 0;20 }21 return 1 + countNodes(root.left) + countNodes(root.right);22 }23}交互式算法学习
从执行步骤真正理解 LeetCode 经典 150
本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。
AlgoViz Lab
完全二叉树的节点个数 · 解法对比
高效统计完全二叉树节点数。
- 测试用例
root = [1,2,3,4,5,6]- 题目分类
- 二叉树
- 解法对比
- 2
普通 DFS 计数
每个节点贡献 1,加左右子树节点数。
- 时间
O(n)- 空间
O(h)
比较左右高度
左右最深高度相等则是满二叉树,可用 2^h−1 直接计算。
- 时间
O(log² n)- 空间
O(log n)