平衡二叉树的解法:主要是求出二叉树的高度,若根节点的左子树的高度与右子树的高度差小于等于1,则表示该二叉树为平衡二叉树
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int data){
this.value = data;
}
}
public static boolean isBalance(Node head){
return getHeight(head, 0) ! = -1;
}
public static int getHeight(Node head, int level){
if(head == null){
return level;
}
int lh = getHeight(head.left, level + 1);
int rh = getHeight(head.right, level + 1);
if(lh == -1 || rh == -1 || Math.abs(lh - rh) > 1){
return -1;
}
}
完全二叉树的解法:若最左的一个节点只有一个左子节点,则其余的同高度的节点都应该是叶节点
public static boolean isComplete(Node head){
if(head == null){
return true;
}
Queue<Node> queue = new LinkedList<Node>();
boolean leaf = false;
Node cur = null;
Node l = null;
Node r = null;
queue.offer(head);
while(!queue.isEmpty){
cur = queue.poll();
l = cur.left;
r = cur.right;
if((leaf && (l != null || r != null)) || (l == null && r != null)){
return false;
}
if(l != null){
queue.offer(l);
}
if(r != null){
queue.offer(r);
}else{
leaf = true;
}
}
}
搜索二叉树的解法:只需要中序遍历整棵二叉树,判断得到的节点序列是否为依次递增即可。