题目链接
https://leetcode-cn.com/problems/count-complete-tree-nodes/
描述
给出一个完全二叉树,求出该树的节点个数。
说明:
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
示例
输入:
1
/ \
2 3
/ \ /
4 5 6
输出: 6
初始代码模板
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
}
}
代码
代码注释看不懂没关系,去看题解,有评论更好懂:
https://leetcode-cn.com/problems/count-complete-tree-nodes/solution/chang-gui-jie-fa-he-ji-bai-100de-javajie-fa-by-xia/
emmm,再说明一下,这些博客是每日刷题,会推荐一些个人认为不错的题解,但是一般不会自己写,毕竟自己绞尽脑汁的东西是比不上大佬们经过锤炼的题解的,写的不好不如不写,建议多看看那些优秀题解,这些博客就当个督促做题就行(虽然没人看~)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
int leftLevel = countLevel(root.left);
int rightLevel = countLevel(root.right);
if (leftLevel == rightLevel) {
//如果当前节点左子树的最大高度和右子树的最大高度相等,那么左子树一定是满二叉树,右子树还不确定
return countNodes(root.right) + (1 << leftLevel);
} else {
//如果当前节点左子树的最大高度和右子树的最大高度不等,一定是右子树高度较低
//但是右子树也是满二叉树,因为最下面一层的叶子节点没蔓延到右子树,左子树不确定
return countNodes(root.left) + (1 << rightLevel);
}
}
//当前节点的高度,从底向上算
private int countLevel(TreeNode root) {
int level = 0;
//利用左子树计算高度
while (root != null) {
level++;
root = root.left;
}
return level;
}
}