Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
第一遍写的时候写的不对。没有规定子树值的上下值。第二遍搞定。一共8分钟。。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
return validateBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private boolean validateBST(TreeNode node, int from, int to) {
if (node == null) {
return true;
} else if (node.val >= to || node.val <= from) {
return false;
} else if (node.left != null && !validateBST(node.left, from, node.val)) {
return false;
} else if (node.right != null && !validateBST(node.right, node.val, to)) {
return false;
}
return true;
}
}
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
return validateBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private boolean validateBST(TreeNode node, int from, int to) {
if (node == null) {
return true;
} else if (node.val >= to || node.val <= from) {
return false;
} else if (node.left != null && !validateBST(node.left, from, node.val)) {
return false;
} else if (node.right != null && !validateBST(node.right, node.val, to)) {
return false;
}
return true;
}
}