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.
- Example 1
2
/ \
1 3
Binary tree
[2,1,3]
, return true. Example 2:
1
/ \
2 3
Binary tree
[1,2,3], return false.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private TreeNode prev = null;
private boolean isValid = false;
public boolean isValidBST(TreeNode root) {
isValid = true;
if (root == null) {
return true;
}
help(root);
return isValid;
}
public void help(TreeNode root) {
if (root == null) {
return;
}
help(root.left);
if (prev != null && prev.val >= root.val) {
isValid = false;
return;
}
prev = root;
help(root.right);
}
}
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if the binary tree is BST, or false
*/
private class ResultType{
boolean isValid;
TreeNode maxNode;
TreeNode minNode;
private ResultType(boolean valid) {
this.isValid = valid;
maxNode = null;
minNode = null;
}
}
public boolean isValidBST(TreeNode root) {
// write your code here
if (root == null) {
return true;
}
ResultType res = helper(root);
return res.isValid;
}
public ResultType helper(TreeNode root) {
if (root == null) {
return new ResultType(true);
}
ResultType left = helper(root.left);
ResultType right = helper(root.right);
if (!left.isValid || !right.isValid) {
return new ResultType(false);
}
//valid -> value
if (left.maxNode != null && left.maxNode.val >= root.val) {
return new ResultType(false);
}
if (right.minNode != null && right.minNode.val <= root.val) {
return new ResultType(false);
}
ResultType res = new ResultType(true);
res.minNode = left.minNode != null ? left.minNode : root;
res.maxNode = right.maxNode != null ? right.maxNode : root;
return res;
}
}