leetcode 力扣 98 验证二叉搜索树

71 阅读1分钟

中序遍历

根据二叉搜索树的性质,判断当前结点是否比中序遍历中的上一个结点要大

lc98.jpeg

迭代

public boolean isValidBST(TreeNode root) {
        Deque<TreeNode> stack = new LinkedList<>();
        long preVal = Long.MIN_VALUE;
        

        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }

            root = stack.pop();
            if (preVal >= root.val) {
                return false;
            }

            preVal = root.val;
            root = root.right;
        }

        return true;
    }

递归

class Solution {
    long pre = Long.MIN_VALUE;

    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }

        if (!isValidBST(root.left)) {
            return false;
        }

        if (pre >= root.val) {
            return false;
        }

        pre = root.val;

        return isValidBST(root.right);
    }
}