public class BTree {
public static void main(String[] args) {
TreeNode root = new TreeNode(6);
TreeNode node2 = new TreeNode(4);
TreeNode node3 = new TreeNode(8);
TreeNode node4 = new TreeNode(3);
TreeNode node5 = new TreeNode(5);
TreeNode node6 = new TreeNode(7);
TreeNode node7 = new TreeNode(9);
root.left = node2;
root.right = node3;
node2.left = node4;
node2.right = node5;
node3.left = node6;
node3.right = node7;
inOrder(root);
System.out.println();
boolean res = isBST(root);
System.out.println(res);
}
public static int minNum = Integer.MIN_VALUE;
static boolean isBST(TreeNode root) {
if (root == null) return true;
isBST(root.left);
if (root.value <= minNum) {
return false;
}else {
minNum = root.value;
}
isBST(root.right);
return true;
}
static void preOrder(TreeNode root) {
if (root == null) return;
System.out.print(root.value + " ");
preOrder(root.left);
preOrder(root.right);
}
static void inOrder(TreeNode root) {
if (root == null) return;
inOrder(root.left);
System.out.print(root.value + " ");
inOrder(root.right);
}
static void postOrder(TreeNode root) {
if (root == null) return;
postOrder(root.left);
postOrder(root.right);
System.out.print(root.value + " ");
}
}
class TreeNode {
int value;
TreeNode left;
TreeNode right;
public TreeNode(int value) {
this.value = value;
}
}
判断搜索二叉树 isBST Binary Search Tree
最新推荐文章于 2024-11-12 21:14:07 发布