98. Validate Binary Search Tree
Copy 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
Input: [2,1,3]
Output: true
Approach #1 Divide & Conquer
Copy public class Solution {
public boolean isValidBST ( TreeNode root) {
if (root == null ) return true ;
return helper(root , Long . MIN_VALUE , Long . MAX_VALUE ) ;
}
private boolean helper ( TreeNode root , long lower , long upper) {
if (root == null ) return true ;
if ( root . val >= upper || root . val <= lower) return false ;
boolean isLeftValidBST = helper( root . left , lower , root . val ) ;
boolean isRightValidBST = helper( root . right , root . val , upper) ;
return isLeftValidBST && isRightValidBST;
}
}
Copy class Solution {
LinkedList < TreeNode > stack = new LinkedList() ;
LinkedList < TreeNode > uppers = new LinkedList() ;
LinkedList < TreeNode > lowers = new LinkedList() ;
public boolean isValidBST ( TreeNode root) {
Integer lower = null , upper = null , val;
update(root , lower , upper) ;
while ( ! stack . isEmpty ()) {
root = stack . poll ();
lower = lowers . poll ();
upper = uppers . poll ();
if (root == null ) continue ;
val = root . val ;
if (lower != null && val <= lower) return false ;
if (upper != null && val >= upper) return false ;
update( root . right , val , upper) ;
update( root . left , lower , val) ;
}
return true ;
}
public void update ( TreeNode root , Integer lower , Integer upper) {
stack . add (root);
lowers . add (lower);
uppers . add (upper);
}
}
Approach #3 No-Recursion, Access nodes from small to large
Copy class Solution {
public boolean isValidBST ( TreeNode root) {
Stack < TreeNode > stack = new Stack <>();
while (root != null ) {
stack . push (root);
root = root . left ;
}
TreeNode lastNode = null ;
while ( ! stack . isEmpty ()) {
TreeNode node = stack . peek ();
if (lastNode != null && lastNode . val >= node . val ) {
return false ;
}
lastNode = node;
if ( node . right == null ) {
node = stack . pop ();
while ( ! stack . isEmpty () && stack . peek () . right == node) {
node = stack . pop ();
}
} else {
node = node . right ;
while (node != null ) {
stack . push (node);
node = node . left ;
}
}
}
return false ;
}
}