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.
Example 2:
1
/ \
2 3
Binary tree [1,2,3]
, return false.
这道题看的答案,第一次用到这种限制max, min bound的方法,很巧妙。注意,判断左右子树的时候,记得要更新max, min bound传递到递归里。留意一下,像Integer.MAX_VALUE,Integer.MIN_VALUE一样,double也有类似的Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
if (root == null){
return true;
}
return helper(root, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);
}
private boolean helper(TreeNode root, double min, double max){
if (root.val <= min || root.val >= max){
return false;
}
if (root.left != null && !helper(root.left, min, root.val)){
return false;
}
if (root.right != null && !helper(root.right, root.val, max)){
return false;
}
return true;
}
}
这道题还有另外一个方法,不过要想到的话要求你对BST的性质要比较熟悉。这个方法利用到了BST对应节点的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这个特点,对BST进行inorder遍历,遍历出来的节点val值就是从小到大排列的。如果出现了list.get(i) >= list.get(i + 1)的情况,就说明不是BST.顺便也复习了一下inorder的recursive的做法。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
if (root == null){
return true;
}
List<Integer> list = new ArrayList<>();
list = inOrder(root, list);
for (int i = 0; i < list.size() - 1; i++){
if (list.get(i) >= list.get(i + 1)){
return false;
}
}
return true;
}
private List<Integer> inOrder(TreeNode root, List<Integer> list){
if (root.left != null){
inOrder(root.left, list);
}
list.add(root.val);
if (root.right != null){
inOrder(root.right, list);
}
return list;
}
}