判断一个树是否是二叉搜索树,用递归或者非递归中序历遍,如果结果是有序递增则返回true
public void visit(TreeNode n, ArrayList<Integer> l){
if(n==null) return;
visit(n.left,l);
l.add(n.val);
visit(n.right,l);
}
public boolean isValidBST(TreeNode root) {
if(root==null) return true;
ArrayList<Integer> l = new ArrayList<Integer>();
visit(root,l);
for(int i=0;i<l.size()-1;i++){
if(l.get(i)>=l.get(i+1)) return false;
}
return true;
}
Update 2015/08/21: 上面的解法很不好,跟好的解法是在递归时使用min 和 max变量。需要注意的一点是下面的答案使用node.val+1或者-1而不是在判断false的时候使用<=和>=是因为node.val可能等于Integer的MAX或者min。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: True if the binary tree is BST, or false
*/
public boolean check(TreeNode node, int min, int max){
if (node == null){
return true;
}
if (node.val < min || node.val > max){
return false;
}
return check(node.left, min, node.val-1) && check(node.right, node.val+1, max);
}
public boolean isValidBST(TreeNode root) {
// write your code here
return check(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
}