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的性質(zhì)要比較熟悉蕊退。這個方法利用到了BST對應(yīng)節(jié)點的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遍歷憔恳,遍歷出來的節(jié)點val值就是從小到大排列的。如果出現(xiàn)了list.get(i) >= list.get(i + 1)的情況净蚤,就說明不是BST.順便也復(fù)習(xí)了一下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;
}
}