基本功,经典题。
虽然是递归解法,但用的却是中序遍历,保证了子节点的必须小于或是大于根节点,所以自己最开始的方法错了。
最后都得用Long.MIN_VALUE,我都要笑哭了。。。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
//private int lastVal = Integer.MIN_VALUE;
private long lastVal = Long.MIN_VALUE;
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
if (!isValidBST(root.left)) {
return false;
}
if (lastVal >= root.val) {
return false;
}
lastVal = root.val;
if (!isValidBST(root.right)) {
return false;
}
return true;
// 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);
}
}