原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn08xg/
解法一:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
return isValid(root,Long.MIN_VALUE,Long.MAX_VALUE);
}
public boolean isValid(TreeNode root,long minValue,long maxValue) {
if (root == null) {
return true;
}
if (root.val <= minValue || root.val >= maxValue) {
return false;
}
return isValid(root.left,minValue,root.val) && isValid(root.right,root.val,maxValue);
}
}
思路:递归二叉树,每一个节点都需要校验当前节点的值大于左子树的值,小于右子树的值,还需要校验一种特殊的情况,如图:
解法二:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
TreeNode pre;
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
// 访问左子树
if (!isValidBST(root.left)) {
return false;
}
// 前一个节点大于或者等于当前节点时,表示不符合二叉搜索树
if (pre != null && pre.val >= root.val) {
return false;
}
pre = root;
// 访问右子树
if (!isValidBST(root.right)) {
return false;
}
return true;
}
}
思路:递归中序遍历,根据二叉搜索树的性质我们知道,中序遍历二叉搜索树,遍历的结果一定是有序的,判断当前节点是否大于中序遍历的前一个节点,也就是判断是否有序,如果不大于直接返回 false。
解法三:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
TreeNode pre;
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
Stack<TreeNode> stack = new Stack();
TreeNode pre = null;
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (pre != null && root.val <= pre.val) {
return false;
}
pre = root;
root = root.right;
}
return true;
}
}
思路:非递归中序遍历,就是不是使用递归的方式来遍历树