[LeetCode]98. 验证二叉搜索树

题目

给定一个二叉树,判断其是不是一个有效的二叉搜索树。网络

假设一个二叉搜索树具备以下特征:code

节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
全部左子树和右子树自身必须也是二叉搜索树。leetcode

来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/validate-binary-search-tree
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。get

题解

由题,中序遍历是严格的递增,则是BST。
不须要将中序遍历结果存储,只需在中序遍历过程当中比较序列临近两元素便可。class

代码

public static boolean isValidBST(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode curNode = root;
        long maxVal = Long.MIN_VALUE;
        while (curNode != null || !stack.isEmpty()) {//
            while (curNode != null) {
                stack.push(curNode);
                curNode = curNode.left;
            }
            curNode = stack.pop();
            if (curNode.val > maxVal) {
                maxVal = curNode.val;
                curNode = curNode.right;//
            } else {
                return false;
            }
        }
        return true;
    }
相关文章
相关标签/搜索