Leetcode 98 Validate Binary Search Tree
Approach 1: Recursion
class Solution {
public boolean helper(TreeNode node, Integer lower, Integer upper) {
if (node == null) return true;
int val = node.val;
if (lower != null && val <= lower) return false;
if (upper != null && val >= upper) return false;
if (! helper(node.right, val, upper)) return false;
if (! helper(node.left, lower, val)) return false;
return true;
}
public boolean isValidBST(TreeNode root) {
return helper(root, null, null);
}
}
Approach 2: Iteration
The above recursion could be converted into iteration, with the help of stack. DFS would be better than BFS since it works faster here.
Approach 3: Inorder traversal
class Solution {
ArrayList<Integer> arr = new ArrayList<>();
public boolean isValidBST(TreeNode root) {
Inorder(root);
for(int i=0; i<arr.size()-1; i++){
if(arr.get(i) >= arr.get(i+1)){
return false;
}
}
return true;
}
public void Inorder(TreeNode node){
if(node == null) return;
Inorder(node.left);
arr.add(node.val);
Inorder(node.right);
}
}
class Solution {
public boolean isValidBST(TreeNode root) {
Stack<TreeNode> stack = new Stack();
double inorder = - Double.MAX_VALUE;
while (!stack.isEmpty() || root != null) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
// If next element in inorder traversal
// is smaller than the previous one
// that's not BST.
if (root.val <= inorder) return false;
inorder = root.val;
root = root.right;
}
return true;
}
}