以根节点右子树的左边界是否等于高度为分界,如果等于,左子树一定满了,可以用公式计算出来,如果不等于,那么右子树满了,计算出来,在递归计算另一部分不满的,递归的baseline就是high==level的时候,因为递归的最后就是一个节点。
/**
* 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;
}
return bs(1,getlh(1,root),root);
}
public int getlh(int level,TreeNode head){
while(head!=null){
level++;
head=head.left;
}
return level-1;
}
public int bs(int level,int high,TreeNode head){
//baseline 此处取的baseline是high=level,最简单的baseline,也可以用别的,这个简单
if(level==high){
return 1;
}
if(getlh(level+1,head.right)==high){
return (1<<(high-level))+bs(level+1,high,head.right);
}else{
return (1<<(high-level-1))+bs(level+1,high,head.left);
}
}
}