代码:
public int countNodes(TreeNode root) {
int h=height(root);
int count=0;
while(root!=null){
if(height(root.right)==h-1){
count+=1<<h;
root=root.right;
}else{
count+=1<<(h-1);
root=root.left;
}
h--;
}
return count;
}
private int height(TreeNode root){
if(root==null) return -1;
return 1+height(root.left);
}
示例图:
解释:
从root
出发向下搜索,当前层高度为h
,计算子树root.right
的高度:
- 如果为
h-1
,说明至少root.left
是complete的,那么计算root.left+root
的node个数n=1<<h
,加到结果中,后期不再看root.left
,root=root.right
; - 如果不为
h-1
,说明root.left
可能不是complete的,而root.right
必定是个高度为h-2的complete树,那么计算root.right+root
的node个数n=1<<(h-1)
,加到结果中,后期不再看root.right
,root=root.left
。