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.
confused what "{1,#,2,3}"
means? >
read more on how binary tree is serialized on OJ.
经典binary tree的题目。用一个区间,初始化为(min, max)。依次用它检查树中的每一点。如果在区间中,就是合理的。否则,返回false。对区间的更新遵守这样的原则:如果是左子树的递归,就更新max为root.val;如果是右子树递归,就更新min为root.val。当然,也可以对树进行中序遍历,然后检查得到的遍历结果是不是有序的。但是这样还需要额外的空间,肯定没有用区间的方法好,就不再赘述了。
具体代码如下:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isValidBSTHelper(TreeNode root, int lowerBound, int upperBound) {
if(root==null) return true;
if(root.val>lowerBound && root.val<upperBound) {
return isValidBSTHelper(root.left, lowerBound, root.val) && isValidBSTHelper(root.right, root.val, upperBound);
}
else return false;
}
public boolean isValidBST(TreeNode root) {
return isValidBSTHelper(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
}
Version 2: Construct an array through in-order traversal. Determine whether this array is sorted or not.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void isValidBST(TreeNode root, ArrayList<Integer> inorder) {
if(root==null) return;
isValidBST(root.left, inorder);
inorder.add(root.val);
isValidBST(root.right, inorder);
return;
}
public boolean isValidBST(TreeNode root) {
ArrayList<Integer> inorder = new ArrayList<Integer>();
isValidBST(root, inorder);
for(int i=0; i<inorder.size()-1; i++) {
if(inorder.get(i)>=inorder.get(i+1)) return false;
}
return true;
}
}