性质:满二叉树的高为h,则节点个数为。
思路:对于一个完全二叉树,从根节点遍历完全二叉树的左子树,得到完全二叉树的树高h,再去查跟节点的右子树的树高。
- 如果右子树到达了整棵树的最深一层,则证明根节点的左子树是满二叉树,节点个数为,递归去获取右子树的节点个数。
- 如果右子树到达了没有整棵树的最深一层,则证明根节点的左子树高度为h-2是满二叉树,节点个数为,递归去获取左子树的节点个数。
public int getNodeNum(Node root){
if(root==null) return 0;
int h=0;
Node temp=root;
while(temp!=null){ // 不断往根节点的左子树底下靠,得到二叉树的树高。
h++;
temp=temp.left;
}
temp=root.right; // 获取根节点的右子树的树高。
int hR=0;
while(temp!=null){
hR++;
temp=temp.left
}
if(h-1==hR){ //如果左右子树同高,则左子树一定是满二叉树、
return Math.pow(2,h-1)+getNodeNum(root.right);
}else{ // 如果,左子树比右子树高,则右子树一定是满二叉树。
return Math.pow(2,h-2)+getNodeNum(root.left);
}
}
//复杂度分析O(log N)*O(log N);每一层只遍历一个,再去遍历子树。