98. Validate Binary Search Tree

一、题目

  1、审题

  

  2、分析

    判断所给二叉树是否时一个二分查找树。(left < top < right)

 

二、解答

  1、思路:

    方法一、

      采用中序遍历,将遍历的节点值放入一个 List 中,再判断 List 中的元素是否时升序的即可。

public boolean isValidBST(TreeNode root) {
    
        if(root == null)
            return true;
        
        List<Integer> list = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.add(cur);
                cur = cur.left;
            }
            
            cur = stack.pop();
            list.add(cur.val);
            cur = cur.right;
        }
        
        int tmp = list.get(0);
        for(int i = 1; i < list.size(); i++) {
            if(list.get(i) < tmp)
                return false;
            tmp = list.get(i);
        }
        
        return true;
    }

  

  方法二、

    采用中序遍历,直接在便利过程中进行判断是否符合二叉查找树条件。(无须用 List 存储结点)

public boolean isValidBST2(TreeNode root) {
        
        if(root == null)
            return true;
        
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode cur = root;
        TreeNode pre = null;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.add(cur);
                cur = cur.left;
            }
            
            cur = stack.pop();
            if(pre != null && pre.val >= cur.val)
                return false;
            pre = cur;
            cur = cur.right;
        }
        
        return true;
    }

    

    方法三、

      利用递归判断 left 是否小于当前结点值,right 是否大于当前结点值。

public boolean isValidBST3(TreeNode root) {
        
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    private boolean isValidBST(TreeNode root, long minValue, long maxValue) {
        
        if(root == null)
            return true;
        
        if(root.val >= maxValue || root.val <= minValue)
            return false;
        
        return isValidBST(root.left, minValue, root.val) && isValidBST(root.right, root.val, maxValue);
    }

 

posted @ 2018-09-26 21:31  skillking2  阅读(89)  评论(0编辑  收藏  举报