Problem

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
A single node tree is a BST

Example
An example:

  2
 / \
1   4
   / \
  3   5
The above binary tree is serialized as {2,1,4,#,#,3,5} (in level order).

思路一(divide & conquer)

  1. assume the left and right trees are valid BST, what are we gonna do for root node
  2. we just only need to make sure that the root node is in the range between its lower bound and higher bound

    public boolean isValidBST(TreeNode root) {
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    private boolean isValidBST(TreeNode root, long low, long high) {
        if (root == null) {
            return true;
        }

        if (root.val <= low || root.val >= high) return false;
        boolean left = isValidBST(root.left, low, root.val);
        boolean right = isValidBST(root.right, root.val, high);

        return left && right;
    }

思路二(inorder successor)

    public boolean isValidBST(TreeNode root) {
        result = true;
        helper(root);
        return result;
    }

    private TreeNode prev;
    private boolean result;

    private void helper(TreeNode root) {
        if (root == null) {
            return;
        }

        helper(root.left);
        if (prev != null && prev.val >= root.val) {
            result = false;
            return;
        }
        prev = root;
        helper(root.right);
    }

results matching ""

    No results matching ""