一、如何判断一颗二叉树是不是搜索二叉树?(左子节点比根节点要小,右子节点要比根节点要大)
中序遍历一下,看结果是否依次升序的就可以了。
Java代码如下:
public static void main(String[] args) {
Node head = new Node(2);
Node firstLeft = new Node(1);
Node firstRight = new Node(3);
head.left = firstLeft;
head.right = firstRight;
System.out.printf(""+CheckBST(head));
}
public static int preValue = Integer.MIN_VALUE;//遍历到的最后一个值
public static boolean CheckBST(Node head){
if (head == null){
return true;
}
boolean leftResult = CheckBST(head.left);
if (!leftResult){
return false;
}
if (head.value <= preValue){
return false;
}else {
preValue = head.value;
}
return CheckBST(head.right);
}
二、如何判断一颗二叉树是否为完全二叉树?
1、层级遍历,遍历到的每一个节点进行检查,如果出现有右节点无左节点则不是。
2、在条件1不出错的情况下,第一次出现如果两个节点不全,也就是只有一个节点的时候,则该节点的后面的节点都是叶子节点。
Java代码如下:
public static boolean checkCST(Node head){
if (head == null){
return true;
}
Queue<Node> queue = new LinkedList();
queue.add(head);
//是否遇见过左右两个孩子不全的节点
boolean leaf = false;
Node l = null;
Node r = null;
while (!queue.isEmpty()){
head = queue.poll();
l = head.left;
r = head.right;
if ( //遇见过左右孩子不全的节点,但是不是叶子节点
(leaf && (r != null || l!=null))
|| //有右节点但是没左节点
(l == null && r !=null)
){
return false;
}
if (l != null){
queue.add(l);
}
if (r != null){
queue.add(r);
}
if (r == null || l==null){
leaf = true;
}
}
return true;
}
三、如何判断一颗二叉树是否为平衡二叉树?
1、平衡二叉树:它是一棵空树或者它的左右两个子树的高度差不超过1,并且左右两颗子树都是一颗平衡二叉树。
2、思路:左右子树都是平衡二叉树、左右子树的高度差不超过1。用递归的思想。
Java代码如下:
public static boolean checkBalanced(Node head){
return process(head).isBalanced;
}
public static class ReturnType{
public boolean isBalanced;
public int height;
public ReturnType(boolean isBalanced, int height) {
this.isBalanced = isBalanced;
this.height = height;
}
}
private static ReturnType process(Node head) {
if (head == null){
//题目中最后的结果需要树的高度和左右是否平衡。
return new ReturnType(true,0);
}
//左右子树都是平衡树
ReturnType lReturnType = process(head.left);
ReturnType rReturnType = process(head.right);
//返回值的树的高度和左右子树的高度差
int height = Math.max(lReturnType.height,rReturnType.height)+1;
boolean isBalanced = lReturnType.isBalanced && rReturnType.isBalanced && Math.abs(lReturnType.height - rReturnType.height)<2;
return new ReturnType(isBalanced,height);
}