1. 题目
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层
为第 h 层,则该层包含 1~ 2h 个节点。
示例 1:
输入:root = [1,2,3,4,5,6]
输出:6
示例 2:
输入:root = []
输出:0
2. 题解
2.1 解法1: 常规递归
class Solution {
public int countNodes(TreeNode root) {
return dfs(root);
}
public int dfs(TreeNode root) {
if (root == null) {
return 0;
}
return dfs(root.left) + dfs(root.right) + 1;
}
}
2.2 解法2: 特殊递归(利用完全二叉树的性质)
来对 root 节点的左右子树进行高度统计,分别记为 left 和 right,有以下两种结果:
-
left == right。这说明,左子树一定是满二叉树,因为节点已经填充到右子树了,左子树必定已经填满了。所以左子树的节点总数我们可以直接得到,是 2^left - 1,加上当前这个 root 节点,则正好是 2^left。再对右子树进行递归统计。
-
left != right。说明此时最后一层不满,但倒数第二层已经满了,可以直接得到右子树的节点个数。同理,右子树节点 +root 节点,总数为 2^right。再对左子树进行递归查找。
关于求二叉树的层数
对于所有二叉树, 可以用以下递归来处理
private int countLevel(TreeNode root){
if(root == null){
return 0;
}
return Math.max(countLevel(root.left),countLevel(root.right)) + 1;
}
但对于完全二叉树, 不用递归, 直接迭代的向左子树寻找即为高度
public int countLevel(TreeNode root) {
if (root == null) {
return 0;
}
int h = 0;
while (root != null) {
root = root.left;
h++;
}
return h;
}
递归版本代码:
class Solution {
public int countNodes(TreeNode root) {
return dfs(root);
}
public int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int left = countLevel(root.left);
int right = countLevel(root.right);
if (left == right) {
// 说明左子树是满的
return dfs(root.right) + (int) Math.pow(2, left);
} else {
return dfs(root.left) + (int) Math.pow(2, right);
}
}
// 计算二叉树的高度
public int countLevel(TreeNode root) {
if (root == null) {
return 0;
}
int h = 0;
while (root != null) {
root = root.left;
h++;
}
return h;
}
}
非递归版本:
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
int left = countLevel(root.left);
int count = 0;
while (root != null) {
int right = countLevel(root.right);
if (right == left) {
count += (1 << left);
root = root.right;
} else {
count += (1 << right);
root = root.left;
}
left--;
}
return count;
}
public int countLevel(TreeNode root) {
if (root == null) return 0;
int h = 0;
while (root != null) {
root = root.left;
h++;
}
return h;
}
}