Validate Binary Search Tree,判断是否是二叉排序树

算法分析:两种方法,一种是中序遍历,然后得到一个序列,看序列是否是有序的。第二种,是用递归。

中序遍历:

public class Solution {
    List<Integer> list = new ArrayList<>();
    public boolean isValidBST(TreeNode root) {
        if(root == null)
        {
            return true;
        }
        inorderTraversal(root);
        for(int i = 0; i < list.size() - 1; i ++)
        {
            if(list.get(i) >= list.get(i+1))
            {
                return false;
            }
        }
        return true;
    }
    public void inorderTraversal(TreeNode root)
    {
        if(root == null)
        {
            return ;
        }
        inorderTraversal(root.left);
        list.add(root.val);
        inorderTraversal(root.right);
    }
}

 递归:

public boolean isValidBST3(TreeNode root) {
	        return isValidBST(root, null, null);
	    }
	    public boolean isValidBST(TreeNode root, Integer min, Integer max)
	    {
	        if(root == null)
	        {
	            return true;
	        }
	        if(min != null && root.val <= min)
	        {
	            return false;
	        }
	        if(max != null && root.val >= max)
	        {
	            return false;
	        }
	        return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);
	    }

 

posted @ 2016-09-02 22:10  32ddd  阅读(209)  评论(0编辑  收藏  举报