1.题目描述:
给你一个二叉树的根节点root,判断其是否是一个有效的二叉搜索树。有效二叉搜索树定义如下:节点的左子树只包含小于当前节点的数。节点的右子树只包含大于当前节点的数。所有左子树和右子树自身必须也是二叉搜索树。
2.递归:
最初写的代码如下第一段,能发现存在问题,不能保证左子树中的所有节点值都小于当前节点,只是满足了左右子节点与当前节点的大小关系。于是想到通过获取当前root节点左子树节点的最大值max,和右子树节点的最小值min,满足max < root.val和min > root.val即可,这种做法涉及到原二叉树的遍历和最大值最小值计算过程中的左右子树遍历,时间和空间复杂度较高。要注意测试用例中的[2147483647]。
class Solution {
public boolean isValidBST(TreeNode root) {
if (root == null) return true;
if (root.left != null && root.left.val >= root.val) return false;
if (root.right != null && root.right.val <= root.val) return false;
return isValidBST(root.left) && isValidBST(root.right);
}
}
/**
* 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 {
private int max = Integer.MIN_VALUE;
private int min = Integer.MAX_VALUE;
public boolean isValidBST(TreeNode root) {
if (root == null) return true;
if (root.left != null) {
int a = getMax(root.left);
max = Integer.MIN_VALUE;//每次计算过max后需要重置
if (a >= root.val) return false;
}
if (root.right != null) {
int b = getMin(root.right);
min = Integer.MAX_VALUE;//每次计算过min后需要重置
if (b <= root.val) return false;
}
return isValidBST(root.left) && isValidBST(root.right);
}
public int getMax(TreeNode root) {
max = Math.max(root.val, max);
if (root.left != null) getMax(root.left);
if (root.right != null) getMax(root.right);
return max;
}
public int getMin(TreeNode root) {
min = Math.min(root.val, min);
if (root.left != null) getMin(root.left);
if (root.right != null) getMin(root.right);
return min;
}
}
3.官解的递归:
说实话这个递归不好想,方法中需要传递(lower,upper)上下限参数,左子树方向传入上限,右子树方向传入下限。程序运行中,会传入上级递归的上限或者下限,并一直被传递下去,从而保证满足二叉搜索树的条件。同时使用Long。
class Solution {
public boolean isValidBST(TreeNode root) {
return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
public boolean isValidBST(TreeNode root, long lower, long upper) {
if (root == null) return true;
if (root.val <= lower || root.val >= upper) return false;
return isValidBST(root.left, lower, root.val) && isValidBST(root.right, root.val, upper);
}
}
4.中序遍历(迭代):
借助二叉搜索树的特点,中序遍历后为升序,对二叉树进行迭代的中序遍历见leetcode94. 二叉树的中序遍历,中间加入大小的判断即可,需要额外引入中序遍历中的前驱节点pre来比较大小。
class Solution {
public boolean isValidBST(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
TreeNode temp = root;
TreeNode pre = null;
while (temp != null || !stack.isEmpty()){
if (temp != null){
stack.push(temp);
temp = temp.left;//left
}else{
temp = stack.pop();
if (pre != null && temp.val <= pre.val) return false;//root
pre = temp;
temp = temp.right;//right
}
}
return true;
}
}
5.中序遍历(递归):
class Solution {
private TreeNode pre = null;
public boolean isValidBST(TreeNode root) {
if (root == null) return true;
if (!isValidBST(root.left)) return false;//left
if (pre != null && root.val <= pre.val) return false;//root
pre = root;
return isValidBST(root.right);//right
}
}