0098. Validate Binary Search Tree

0098. Validate Binary Search Tree #

题目 #

  • 给定二叉树根节点 root,判断其是否是一个有效的 BST
  • 有效 BST 定义如下
    • 节点的左子树只包含 小于 当前节点的数
    • 节点的右子树只包含 大于 当前节点的数
    • 所有左子树和右子树自身也须是 BST

思路 #

中序遍历 #

代码 #

中序遍历+列表 #

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 void reverse(TreeNode root, List<Integer> values) {
        if (root == null) return;
        traverse(root.left, values);
        values.add(root.val);
        traverse(root.right, values);
    }
    public boolean isValidBST(TreeNode root) {
        List<Integer> values = new LinkedList<>();
        traverse(root, values);
        for (int i = 0; i < values.size() - 1; i++) {
            if (values.get(i) >= values.get(i + 1)) return false;
        }
        return true;
    }
}

中序遍历+全局变量 #

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 {
    private long pre = Long.MIN_VALUE;
    public boolean traverse(TreeNode root) {
        if (root == null) return true;
        boolean ans = traverse(root.left) && this.pre < root.val;
        if (ans == false) return false;
        this.pre = root.val;
        return traverse(root.right);
    }
    public boolean isValidBST(TreeNode root) {
        return traverse(root);
    }
}

致谢https://leetcode.cn/problems/validate-binary-search-tree/solutions/2082978/yan-zheng-er-cha-sou-suo-shu-di-gui-fa-b-zt9r/ #

PlanB