Description
牛客网 2018校招真题 BST判定
Solving Ideas
解决思路与《剑指offer》二叉搜索树与双向链表 类似,可以在中序遍历的同时将结点的值保存到一个数组中,最后判断数组元素是否升序的,如果是升序的,则该树是BST,否则不是。
这里遍历时并不保存结点值,而是使用了一个变量curMax[0],用来表示已遍历过的结点的最大值。
Solution
import java.util.LinkedList;
import java.util.Scanner;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
/**
* 如果BST是正确的,那么在进行中序遍历时,结点值应该是递增的
*
* @author wylu
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
TreeNode root = new TreeNode(scanner.nextInt());
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode curRoot = queue.poll();
String str = scanner.next();
int left = Integer.valueOf(str.substring(str.indexOf(':') + 1, str.indexOf('|')));
int right = Integer.valueOf(str.substring(str.indexOf('|') + 1));
if (left != -1) {
curRoot.left = new TreeNode(left);
queue.offer(curRoot.left);
}
if (right != -1) {
curRoot.right = new TreeNode(right);
queue.offer(curRoot.right);
}
}
int res = isBinarySearchTree(root, new int[1]) ? 1 : 0;
System.out.println(res);
}
private static boolean isBinarySearchTree(TreeNode root, int[] curMax) {
if (root == null) return true;
if (root.left == null) return true;
if (root.left.val > root.val || !isBinarySearchTree(root.left, curMax)) return false;
//如果左子树的最大值比当前根结点的值大
if (curMax[0] > root.val) return false;
if (root.right == null) return true;
if (root.right.val < root.val || !isBinarySearchTree(root.right, curMax)) return false;
//更新已遍历结点的最大值
curMax[0] = Math.max(curMax[0], root.right.val);
return true;
}
}