问题 :222. 完全二叉树的节点个数
给出一个完全二叉树,求出该树的节点个数。
说明:
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
分析
分析:利用完全二叉树的特点进行加速,一种是剪枝的方式,一种的二分的方式。二分的方式代码优美而且好理解,这里我是直接copy了LeetCode评论区的大佬的解法。
Code
// 二分
class Solution {
public int countNodes(TreeNode root) {
/**
完全二叉树的高度可以直接通过不断地访问左子树就可以获取
判断左右子树的高度:
如果相等说明左子树是满二叉树, 然后进一步判断右子树的节点数(最后一层最后出现的节点必然在右子树中)
如果不等说明右子树是深度小于左子树的满二叉树, 然后进一步判断左子树的节点数(最后一层最后出现的节点必然在左子树中)
**/
if (root==null) return 0;
int ld = getDepth(root.left);
int rd = getDepth(root.right);
if(ld == rd) return (1 << ld) + countNodes(root.right); // 1(根节点) + (1 << ld)-1(左完全左子树节点数) + 右子树节点数量
else return (1 << rd) + countNodes(root.left); // 1(根节点) + (1 << rd)-1(右完全右子树节点数) + 左子树节点数量
}
private int getDepth(TreeNode r) {
int depth = 0;
while(r != null) {
depth++;
r = r.left;
}
return depth;
}
// 剪枝方法
class Solution {
/*
执行结果:
通过
显示详情
执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:40.5 MB, 在所有 Java 提交中击败了98.37% 的用户
*/
int curHeight = 0, lackNode = 0, flag = 0;
public int countNodes(TreeNode root) {
if (root == null) return 0;
TreeNode temp = root;
int height = 0;
// 获得高度
while (temp != null) {
height++;
temp = temp.left;
}
travel(root,height);
return (1 << height) -1 - lackNode;
}
public int travel(TreeNode root,int height) {
if (flag == 1 || root == null) return 1;
curHeight++;
// 倒数第二层节点
if (curHeight == height-1) {
if (root.left == null) lackNode += 2;
else if (root.right == null) lackNode += 1;
if (root.right != null || root.left != null) {
// 结束递归
flag = 1;
return 1;
}
} else {
// 不访问叶子节点
travel(root.right,height);
travel(root.left,height);
}
curHeight--;
return 0;
}
}