Problem:
Given a binary tree, determine if it is a valid binary search tree (BST).
Explanation:
判断一棵树是否为BST
My Thinking:
左结点范围:(上个结点的下限,上个结点的值)
右结点范围:(上个结点的值,上个结点的上限)
My Solution:
class Solution {
public boolean isValidBST(TreeNode root) {
return check(root,null,null);
}
public boolean check(TreeNode root,Integer low,Integer high){
if(root==null)
return true;
if(low!=null && root.val<=low)
return false;
if(high!=null && root.val>=high)
return false;
return check(root.left,low,root.val) && check(root.right,root.val,high);
}
}
Optimum Thinking:
使用中序遍历,一旦发现当前值比上一个值小,就返回false
Optimum Solution:
class Solution {
private Integer preval=null;
public boolean isValidBST(TreeNode root) {
if(root==null)
return true;
if(!isValidBST(root.left))
return false;
if(preval!=null && root.val<=preval)
return false;
preval=root.val;
if(!isValidBST(root.right))
return false;
return true;
}
}