Validate Binary Search Tree
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.
解题关键:不能只比较当前root.val与left.val和right.val满不满足BST的定义,需要在递归中记录上一层根节点的值来检测是否满足BST有效性。
Example:
5
/ \
4 6
/ \
3 7
这是一个无效的BST,虽然4的左右孩子都满足 3 < 4 < 7,但是7大于4的根节点5.
Solution 1: Recursive Traversal
Time Complexity: O(n) Space Complexity: O(1)
public class Solution {
public boolean isValidBST(TreeNode root) {
return isValid(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private boolean isValid(TreeNode root, int min, int max){
if(root == null){
return true;
}
if(root.val <= min || root.val >= max){
return false;
}
return isValid(root.left, min, root.val) && isValid(root.right, root.val, max);
}
}
以上代码有一个Bug,在极端情况下,root.val == Integer.MAX_VALUE or root.val == Integer.MIN_VALUE 以上代码会无法正确判断。
先用笨办法解决这个Bug,让我们看看Solution2.
Solution2: In-order Traversal
Time Complexity: O(n) Space Complexity: O(n)
public class Solution {
public boolean isValidBST(TreeNode root) {
List<Integer> in = inorder(root);
for(int i = 1; i < in.size(); i++){
if(in.get(i) <= in.get(i - 1)){
return false;
}
}
return true;
}
private List<Integer> inorder(TreeNode root){
List<Integer> result = new ArrayList<Integer>();
if(root == null){
return result;
}
List<Integer> left = inorder(root.left);
List<Integer> right = inorder(root.right);
result.addAll(left);
result.add(root.val);
result.addAll(right);