Algorithm/src/main/java/tree/CountNodes.java

50 lines
1.7 KiB
Java
Raw Normal View History

2025-05-17 14:14:02 +08:00
package tree;
/**
* 题目 222. 完全二叉树的节点个数 (countNodes)
* 描述给你一棵 完全二叉树 的根节点 root 求出该树的节点个数
* 完全二叉树 的定义如下在完全二叉树中除了最底层节点可能没填满外其余每层节点数都达到最大值并且最下面一层的节点都集中在该层最左边的若干位置若最底层为第 h 从第 0 层开始则该层包含 1~ 2h 个节点
*
示例 1
输入root = [1,2,3,4,5,6]
输出6
* 链接https://leetcode.cn/problems/count-complete-tree-nodes/
*/
//没想出小于o(n)的方法
public class CountNodes {
public int countNodes(TreeNode root) {
// 空树直接返回 0
if (root == null) {
return 0;
}
// 用两个指针分别遍历左子树最左侧和右子树最右侧,
// 目的是快速判断当前子树是否为满二叉树
TreeNode l = root, r = root;
int hl = 0, hr = 0;
// 计算左子树从根到最左叶节点的高度
while (l != null) {
l = l.left;
hl++;
}
// 计算右子树从根到最右叶节点的高度
while (r != null) {
r = r.right;
hr++;
}
// 如果左右高度相同,则说明这是一棵满二叉树
// 满二叉树节点数 = 2^h - 1
if (hl == hr) {
// 使用位运算更高效1 << hl 相当于 2^hl
return (1 << hl) - 1;
}
// 否则,当前树不是满二叉树,
// 则根据「根 + 左子树节点数 + 右子树节点数」递归计算
return 1 + countNodes(root.left) + countNodes(root.right);
}
}