Q222:满二叉树结点个数
/**
* 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 h = getLevel(root,1);
return so(root,1,h);
}
/*
*/
public int so(TreeNode root,int h,int sumh){
if(h==sumh){
return 1;
}
//当当前节点的右子树的深度==sumh,说明左子树是满二叉树,则可以根据公式求出左子树个数2^(maxh-h)-1 再加上父节点
//+1 = 2^(maxh-h),然后对右子树递归求解
//否则
//当当前节点的右子树的深度==sumh-1,说明右子树是满二叉树,则可以根据公式求出左子树个数2^(maxh-h-1)-1 再加上父节点
//+1 = 2^(maxh-h-1),然后对左子树递归求解
if(getLevel(root.right,h+1)==sumh){
return (1<<(sumh-h)) + so(root.right,h+1,sumh);
}else{
return (1 << (sumh-h-1)) + so(root.left,h+1,sumh);
}
}
// 求当前字数的最大层数
public int getLevel(TreeNode node,int h){
int count=h;
while(node!=null){
count++;
node = node.left;
}
return count-1;
}
}