题目描述
题解
/**
* 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
* }
* }
*/
// 非递归的中序遍历
//
// BST的中序遍历是升序的。构建一个pre保存上一次结点的值,注意这里一定要设置成
// double pre = -Double.MAX_VALUE,测试用例会卡这个点。
// 在中序遍历取值时,将当前指针指向结点的值与pre对比,如果上一个结点值pre
// 居然大于等于当前结点值cur.cal,直接返回false,否则,递归结束返回true。
class Solution {
double pre = -Double.MAX_VALUE
public boolean isValidBST(TreeNode root) {
return inOrderNR(root)
}
private boolean inOrderNR(TreeNode root) {
TreeNode cur = root
Stack<TreeNode> stack = new Stack<>()
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur)
cur = cur.left
}
cur = stack.pop()
if (cur.val <= pre)
return false
pre = cur.val
cur = cur.right
}
return true
}
}
// 递归的中序遍历
// 意思是一样的。
// 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:38.2 MB, 在所有 Java 提交中击败了45.27%的用户
class Solution {
double pre = -Double.MAX_VALUE
boolean res = true
public boolean isValidBST(TreeNode root) {
inOrder(root)
return res
}
private void inOrder(TreeNode root) {
if (root == null)
return
if (root.left != null)
inOrder(root.left)
if (root.val <= pre)
res = false
pre = root.val
if (root.right != null)
inOrder(root.right)
}
}