Validate Binary Search Tree

Question(LC.98)

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

  • 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.

Example

I: [2,1,3]
    2
   / \
  1   3
O: true
I: [1,2,3]
    1
   / \
  2   3
O: false

Lesson: ask for more complicate examples

Analysis 1

Ez. We can just do preorder traversal. Check left.val and right.val, if both valid, recursive visit both nodes.

Code

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

    // check left and right
    if (root.left != null && root.left.val >= root.val) {
        return false;
    }
    if (root.right != null && root.right.val <= root.val) {
        return false;
    }

    // both valid, visit both
    return isValidBST(root.left) && isValidBST(root.right);
}

Why this greedy approach didn't work?

Analysis 2

Consider following example

I: [10,5,15,null,null,6,20]
      10
     /  \
    5   15
       /  \
      6   20

Each node represents an interval on the number line. We want to check if the left and right node are within this interval.

Code 2

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

    return validBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}

private boolean validBST(TreeNode root, int Lo, int Hi) {
    // base case
    if (root == null) {
        return true;
    }

    // check root
    if (!withInBound(root.val, Lo, Hi)) {
        return false;
    }

    // visit both
    boolean validLeft = validBST(root.left, Lo, root.val);
    boolean validRight = validBST(root.right, root.val, Hi);

    return validLeft && validRight;
}

private boolean withInBound(int val, int Lo, int Hi) {
    return (val > Lo && val < Hi);
}

results matching ""

    No results matching ""