题目要求:
如标题:
假设该树没有重复的节点
分析:
所谓的二分搜索树,就是任意一个节点满足,大于左孩子,小于右孩子。所以二分搜索树满足这样的一个性质:中序遍历之后的二叉树是顺序的。所以我们这里实现的思路是,改写二叉树的非递归版本的,来校验当前值和前一个值的大小关系。
代码实现:
package com.isea.brush.tree;
import java.util.Stack;
/**
* 判断一棵树是否是一颗二分搜索树
*/
public class IsBinarySearchTree {
private static class Node {
private Integer data;
private Node left;
private Node right;
public Node(int data) {
this.data = data;
}
}
public static boolean isBST(Node head) {
return inOrder(head);
}
/**
* 中序遍历的黄金口诀:当前节点为空,从栈中弹出一个元素,当前节点向右移动;当前节点不为空,压栈,当前节点向左移动
* @param head
* @return
*/
public static boolean inOrder(Node head) {
int lastData = Integer.MIN_VALUE;
if (head != null) {
Stack<Node> stack = new Stack<Node>();
while (!stack.isEmpty() || head != null) {
if (head != null) {
stack.push(head);
head = head.left;
} else {
head = stack.pop();
if (head.data < lastData) {
return false;
}
lastData = head.data;
head = head.right;
}
}
}
return true;
}
public static void main(String[] args) {
Node head = new Node(5);
head.left = new Node(3);
head.right = new Node(8);
head.left.left = new Node(2);
head.left.right = new Node(4);
System.out.println(isBST(head)); // true
}
}
此外我们还可以使用递归的方式来做,需要额外使用一个队列,中序递归时,将数据添加到队列中,然后在弹出队列中的元素,依次和上一个元素做比对,具体的代码如下:
package com.isea.brush.tree;
import java.util.LinkedList;
/**
* 判断一棵树是否是一颗二分搜索树
* 递归的解法
*/
public class IsBinarySearchTree {
static LinkedList<Integer> queue = new LinkedList<Integer>();
private static class Node {
private Integer data;
private Node left;
private Node right;
public Node(int data) {
this.data = data;
}
}
public static void inOrderRec(Node head) {
if (head == null) {
return;
}
inOrderRec(head.left);
queue.add(head.data);
inOrderRec(head.right);
}
public static boolean isB(Node head) {
inOrderRec(head);
int lastValue = Integer.MIN_VALUE;
while (!queue.isEmpty()) {
Integer value = queue.poll();
if (value < lastValue) {
return false;
}
lastValue = value;
}
return true;
}
public static void main(String[] args) {
Node head = new Node(5);
head.left = new Node(3);
head.right = new Node(8);
head.left.left = new Node(2);
head.left.right = new Node(4);
System.out.println(isB(head)); // true
}
}