搜索二叉树:它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
即 二叉搜索树的中序遍历一定是从小到大排好序的
所以判断一棵树是否是二叉搜索树 查看其中序遍历是否为从小排到大的即可
修改非递归版本的中序遍历代码。设一个pre用来保存上一次的节点 在输出位置判断pre是否大于此应该输出的节点
public static boolean isBST(Node head) {
if (head == null)
return true;
Stack<Node> stack = new Stack<Node>();
int pre=Integer.MIN_VALUE;
while (!stack.isEmpty()||head!=null) {
while (head != null) {
stack.push(head);
head = head.left;
}
head = stack.pop();
if(head.value <pre) return false;
//System.out.print(head.value+" ");
pre=head.value;
head = head.right;
}
return true;
}
在此暂时收录一个方法二:木的解析...
public static boolean isBST2(Node head) {
if (head == null) {
return true;
}
boolean res = true;
Node pre = null;
Node cur1 = head;
Node cur2 = null;
while (cur1 != null) {
cur2 = cur1.left;
if (cur2 != null) {
while (cur2.right != null && cur2.right != cur1) {
cur2 = cur2.right;
}
if (cur2.right == null) {
cur2.right = cur1;
cur1 = cur1.left;
continue;
} else {
cur2.right = null;
}
}
if (pre != null && pre.value > cur1.value) {
res = false;
}
pre = cur1;
cur1 = cur1.right;
}
return res;
}
完整测试代码:
package BinaryTree;
import java.util.Stack;
import BinaryTree.threePrintTree.Node;
//判断一个数是不是二叉搜索树
public class SerchTree {
public static boolean isBST(Node head) {
if (head == null)
return true;
Stack<Node> stack = new Stack<Node>();
int pre=Integer.MIN_VALUE;
while (!stack.isEmpty()||head!=null) {
while (head != null) {
stack.push(head);
head = head.left;
}
head = stack.pop();
if(head.value <pre) return false;
//System.out.print(head.value+" ");
pre=head.value;
head = head.right;
}
return true;
}
public static boolean isBST2(Node head) {
if (head == null) {
return true;
}
boolean res = true;
Node pre = null;
Node cur1 = head;
Node cur2 = null;
while (cur1 != null) {
cur2 = cur1.left;
if (cur2 != null) {
while (cur2.right != null && cur2.right != cur1) {
cur2 = cur2.right;
}
if (cur2.right == null) {
cur2.right = cur1;
cur1 = cur1.left;
continue;
} else {
cur2.right = null;
}
}
if (pre != null && pre.value > cur1.value) {
res = false;
}
pre = cur1;
cur1 = cur1.right;
}
return res;
}
public static void main(String[] args) {
Node head = new Node(4);
head.left = new Node(2);
head.right = new Node(6);
head.left.left = new Node(1);
head.left.right = new Node(3);
head.right.left = new Node(5);
//printTree(head);
System.out.println(isBST2(head));
//System.out.println(isCBT(head));
}
}