题目描述
给定一个完全二叉树,统计节点数
输出描述:
输出个数
要求时间复杂度小于O(n);
解法一:递归
public int nodeNum(TreeNode head){
if(head==null) return 0;
return get(head,1,findLeftHeight(head,1));
}
public int get(TreeNode head,int l,int h){
if(l==h) return 1;
if(findLeftHeight(head.right,l+1)==h){
return (1<<h-l)+get(head.right,l+1,h);
}else{
return (1<<h-l-1)+get(head.left,l+1,h);
}
}
public int findLeftHeight(TreeNode head,int l){
while(head!=null){
head = head.left;
l++;
}
return l-1;
}