1. 完全二叉树
若设二叉树的深度为h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。
它的深度至少是lg(N+1)。最多也不会超过lg(2N)。
a) 判断一棵树是否是完全二叉树:按层遍历
- 如果一个结点,左右孩子都不为空,则pop该节点,将其左右孩子入队列;
- 如果一个结点,左为空,右不为空,则该树一定不是完全二叉树;
- 如果一个结点,左孩子不为空,右孩子为空;或者左右孩子都为空;则该节点之后的队列中的结点都为叶子节点;该树才是完全二叉树,否则就不是完全二叉树;
public static boolean isCBT(TreeNode root){
if(root == null) return true;
Queue<Integer> queue = new LinkedList<>();
//叶子结点标志位,遇到了左子树非空 右子树空的节点设为true,若要为完全二叉树,则其后所有节点必须为叶子结点
boolean isLeaf = false;
TreeNode l = null;
TreeNode r = null;
queue.offer(root);
while(!queue.isEmpty()){
root = queue.poll();
l = root.left;
r = root.right;
if((isLeaf && (l != null && r != null)) || (l == null && r != null))
return false;
if(l != null){
queue.add(l);
}
if(r != null)
queue.add(r);
else
isLeaf = true;
}
return true;
}
b) 求完全二叉树的节点个数,复杂度低于0(n)
对于满二叉树,高度n,,节点为2^n - 1
一个节点右子树的左边界到达最后一层,则其左边界是满的;若没到,则右子树是少一层的满二叉树。
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
int left = countLevel(root.left);
int right = countLevel(root.right);
if(left == right){
return countNodes(root.right) + (1<<left);
}else{
return countNodes(root.left) + (1<<right);
}
}
private int countLevel(TreeNode root){
int level = 0;
while(root != null){
level++;
root = root.left;
}
return level;
}
2. 平衡二叉树
判断是否为二叉搜索树
boolean isBalance = true;
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
height(root);
return isBalance;
}
private int height(TreeNode root){
if(root == null) return 0;
int left = height(root.left);
int right = height(root.right);
if(Math.abs(left - right) > 1){
isBalance = false;
}
return Math.max(left, right) + 1;
}