问题
给出一个完全二叉树,求出该树的节点个数。
例子
思路
-
方法1
不管是不是完全二叉树都可以用
-
方法2
利用完全二叉树特性:满二叉树个数:2^h-1,左右子树高度差不超过1
如果左子树高度==右子树高度,则:左子树是满的,结点个数为:2^dep_left-1+1(根),然后计算右子树的个数
如果左子树高度!=右子树高度,则说明右子树是满的,但是高度比左子树低,结点个数为:2^dep_right-1+1(根),然后计算左子树的个数
代码
//方法1
class Solution {
public int countNodes(TreeNode root) {
if(root==null) return 0;
return countNodes(root.left)+countNodes(root.right)+1;
}
}
//方法2
class Solution {
public int countNodes(TreeNode root) {
if(root==null) return 0;
// return countNodes(root.left)+countNodes(root.right)+1;
int depl = getDepth(root.left);
int depr = getDepth(root.right);
if(depl==depr) return (1<<depl)+countNodes(root.right);
else return (1<<depr)+countNodes(root.left);
}
// public int getDepth(TreeNode root) {
// if(root==null) return 0;
// return Math.max(getDepth(root.left),getDepth(root.right))+1;
// }
//求最大高度也可以优化:利用完全二叉树的特性,最深一层肯定是在左子树上
public int getDepth(TreeNode root) {
int res = 0;
while(root!=null) {
res++;
root=root.left;
}
return res;
}
}