98. Verify the binary search tree (java implementation) --LeetCode

topic:

Given a binary tree, judge whether it is a valid binary search tree.

Suppose a binary search tree has the following characteristics:

  • The left subtree of the node only contains numbers less than the current node.
  • The right subtree of the node only contains numbers greater than the current node.
  • All left subtrees and right subtrees themselves must also be binary search trees.

Example 1:

输入:
    2
   / \
  1   3
输出: true

Example 2:

输入:
    5
   / \
  1   4
     / \
    3   6

输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5 ,但是其右子节点值为 4 。

Solution 1: In-order traversal

    /**
     * 思路:
     * 二叉搜索树的中序遍历是有序的
     * 先进行中序遍历,之后遍历中序结果看是否有序
     */
    public boolean isValidBST(TreeNode root) {
    
    
        ArrayList<Integer> list = new ArrayList<>();
        inOrderRecursive(root,list);
        for (int i=1;i<list.size();i++){
    
    
            if (list.get(i)<=list.get(i-1))return false;
        }
        return true;
    }

    private void inOrderRecursive(TreeNode root, ArrayList<Integer> list) {
    
    
        if (root==null)return;
        inOrderRecursive(root.left,list);
        list.add(root.val);
        inOrderRecursive(root.right,list);
    }

Time complexity: On

Space complexity: O1

Insert picture description here

Solution 2: Recursion

/**
 * 思路:
 * 必须考虑全部节点这个关键问题。所以当前节点一定要满足,小于最大的,大于最小的
 * 递归left,当前节点是最大的,右边当前节点是最小的(这样就能避免,只考虑父亲节点的左右节点大小关系)
 * [5,4,6,null,null,3,7]
 */
    public boolean isValidBST(TreeNode root) {
    
    
        return recursive(root,null,null);
    }

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

Time complexity: On

Space complexity: O1

Insert picture description here

Solution 3: stack

    /**
     * 思路:
     * 当前节点有左节点就不断的入栈,找到最左,就是最小的值
     * 如果当前值小于最小值返回false
     * 迭代这个过程,直到栈为null
     */
    public boolean isValidBST(TreeNode root) {
    
    
        ArrayDeque<TreeNode> stack = new ArrayDeque<>();
        double inorder=-Double.MAX_VALUE;
        while (!stack.isEmpty()||root!=null){
    
    
            while (root!=null){
    
    
                stack.push(root);
                root=root.left;
            }
            root=stack.pop();
            if (root.val<=inorder)return false;
            inorder=root.val;
            root=root.right;
        }
        return true;
    }

Time complexity: On

Space complexity: On
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_38783664/article/details/112860699