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.
10/31
Solution 1:
use the inorder traversal with stack(no recursion) and returns false immediately after a node > its inorder predecessor;
/**
* 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) {
// solution 1: in order traversal
if(root == null) return true;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root, prev = null;
while(p != null || !stack.empty()){
while(p != null){
stack.push(p);
p = p.left;
}
TreeNode top = stack.pop();
if(prev != null && prev.val >= top.val) return false;
prev = top;
p = top.right;
}
return true;
}
}
时间是O(n): 扫描所有的node
空间是O(n)/O(1): 如果用Morris Traversal那么复杂度就是O(1)
Solution 2:
recursion: each recursion should return the range to check
/**
* 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) {
if(root == null) return true;
else return isValidBSTRec(root, new int[2]);
}
private boolean isValidBSTRec(TreeNode root, int[] range){
// note that root cannot be null
int[] left = new int[2];
int[] right = new int[2];
range[0] = root.val;
range[1] = root.val;
if(root.left != null){
if(!isValidBSTRec(root.left, left)) return false; // err2: should call the recursive form
// update the range
if(root.val <= left[1]) return false;
range[0] = left[0];
}
if(root.right != null){
if(!isValidBSTRec(root.right, right)) return false;
// update the range
if(root.val >= right[0]) return false; // err1: ask if it can be =?
range[1] = right[1];
}
return true;
}
}
The time complexity again is O(n): check all the nodes
The space complexity is O(n): maintain two range values for each node