其他分享
首页 > 其他分享> > LeetCode 98. 验证二叉搜索树

LeetCode 98. 验证二叉搜索树

作者:互联网

98. 验证二叉搜索树

给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。

有效 二叉搜索树定义如下:

示例 1:

img

输入:root = [2,1,3]
输出:true

示例 2:

img

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

提示:

二、方法一

递归利用二叉搜索树的性质进行判断

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public boolean isValidBST(TreeNode root, long low, long uper) {
        if (root == null) {
            return true;
        }
        if (root.val <= low || root.val >= uper) {
            return false;
        }
        return isValidBST(root.left, low, root.val) && isValidBST(root.right, root.val,uper);
    }
}

复杂度分析

三、方法二

中序遍历,如果是二叉搜索树,中序遍历就是递增的

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        double temp = -Double.MAX_VALUE;
        Deque<TreeNode> stack = new ArrayDeque<>();
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.poll();
            if (root.val <= temp) {
                return false;
            }
            temp = root.val;
            root = root.right;
        }
        return true;
    }
}

复杂度分析

标签:right,TreeNode,val,二叉,98,节点,root,LeetCode,left
来源: https://blog.csdn.net/qq_43803285/article/details/122723145