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

递归 二叉搜索树转化为有序数组

class Solution {

    List<Integer> ans = new ArrayList<>();

    public boolean isValidBST(TreeNode root) {
        traversal(root);
        for (int i = 1; i < ans.size(); i++) {
            if (ans.get(i) <= ans.get(i-1)) {
                return false;
            }
        }
        return true;
    }

    // 二叉搜索树的中序遍历的输出是一个有序数组
    private void traversal(TreeNode node) {
        if (node == null) return;
        traversal(node.left);
        ans.add(node.val);
        traversal(node.right);
    }
}

递归 中序遍历过程直接判断

使用一个指针记录中序遍历的前一个节点,需要注意要验证当前节点的左子树的所有节点都小于当前节点,当前节点的右子树都大于当前节点才能说明当前节点是一颗二叉搜索树

class Solution {

    TreeNode pre = null;

    public boolean isValidBST(TreeNode root) {
        if (root == null) return true;
        boolean left = isValidBST(root.left);
        if (pre != null && root.val <= pre.val) return false;
        pre = root;
        boolean right = isValidBST(root.right);
        return left && right;
    }
}

迭代

使用栈模拟中序遍历


class Solution {

    public boolean isValidBST(TreeNode root) {
        TreeNode cur = root;
        TreeNode pre = null;
        LinkedList<TreeNode> stack = new LinkedList<>();
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                cur = stack.pop();
                if (pre != null && cur.val <= pre .val) 
                return false;
                pre = cur;
                cur = cur.right;
            }
        }
        return true;
    }
}
posted @ 2020-11-04 11:42  消灭猕猴桃  阅读(72)  评论(0编辑  收藏  举报