222. 完全二叉树的节点个数
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-complete-tree-nodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 给出一个完全二叉树,求出该树的节点个数。
题目**
说明:
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
示例:
输入:
1
/ \
2 3
/ \ /
4 5 6
输出: 6
1、递归1逐个累加**
思想**
递归边界为结点越过叶结点变为空;递归主体为cnt++
代码**
class Solution {
public int countNodes(TreeNode root) {
int cnt = 0;
if(root != null){
cnt++;
cnt += countNodes(root.left);
cnt += countNodes(root.right);
}
return cnt;
}
}
2、递归2二叉树性质**
思想**
如果极左和极右高度一致,那么为满二叉树,直接用公式求解即可
否则递归到叶结点之后(递归边界),返回0
代码**
/*
2、二叉搜索
*/
class Solution {
public int countNodes(TreeNode root) {
int cnt = 0;
if(root == null){//特殊边界和递归边界,越过叶结点,返回0
return 0;
}
int ldep = lDepth(root);
int rdep = rDepth(root);
if(ldep == rdep){//左右子树高度相等时为满二叉树可以直接求子树结点数;最差到叶结点高度为1的满二叉树
return (int)Math.pow(2, ldep) - 1;
}
else{
return 1 + countNodes(root.left) + countNodes(root.right);//递归
}
}
public int lDepth(TreeNode root) {//获取高度
int cnt = 0;
while(root != null){
cnt++;
root = root.left;
}
return cnt;
}
public int rDepth(TreeNode root) {//获取右子树高度
int cnt = 0;
while(root != null){
cnt++;
root = root.right;
}
return cnt;
}
}