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.
Solution1:Recursively check range
Recursively check every node to see if it is in its valid range
// trick: Use Long.MIN_VALUE to handle the input is Integer.MAX/MIN_VALUE
Time Complexity: O(N)
Space Complexity: worst O(层数N) ,Avg:O(层数logn) 作为递归缓存
Solution2:In-order traversal
In-order 中序遍历,检查是否持续递增
Time Complexity: O(N)
Space Complexity: worst O(结点数:N) ,Avg:O(层数:logN) stack使用
Solution1 Code:
class Solution1 {
public boolean isValidBST(TreeNode root) {
return isValid(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean isValid(TreeNode node, long min, long max) {
if(node == null) return true;
if(node.val <= min || node.val >= max) return false;
else return isValid(node.left, min, node.val) && isValid(node.right, node.val, max);
}
}
Solution2 Code:
class Solution2 {
public boolean isValidBST(TreeNode root) {
if (root == null) return true;
Stack<TreeNode> stack = new Stack<>();
TreeNode pre = null;
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if(pre != null && root.val <= pre.val) return false;
pre = root;
root = root.right;
}
return true;
}
}