Question

Formatted question description: https://leetcode.ca/all/98.html

98	Validate Binary Search Tree

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.

@tag-tree

Algorithm

Make use of the nature of BST, bring the maximum and minimum values of the system during initialization, and replace them with their own node values in the recursive process.

The use of long instead of int is to include the boundary conditions of int.

For below BFS solution, we can also define a new data structure MyNode


class MyNode {

    TreeNode node;
    int upper;
    int lower;
}

Then initiate as

new MyNode(node, Integer.Max, Integer.Min)

And enqueue as

queue.offer(new MyNode(node.left, lower, currentNode.val))
queue.offer(new MyNode(node.right, currentNode.val, upper))

Note: remember below in invalid, 7 should go right of 5

   5
  / \
 1   8
  \   \
   7   10

Code

Java

import java.util.LinkedList;

public class Validate_Binary_Search_Tree {

	/**
	 * Definition for a binary tree node.
	 * public class TreeNode {
	 *     int val;
	 *     TreeNode left;
	 *     TreeNode right;
	 *     TreeNode(int x) { val = x; }
	 * }
	 */

	public class Solution { // dfs

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

		public boolean isValidBST(TreeNode root, long min, long max) { // int will be overflow by input [2147483647]
			if (root == null) {
				return true;
			}
			if (root.val >= max || root.val <= min) { // @note: must be <= and >=, eg. [1,1]
				return false;
			}

			// below code, check with left/right children not necessary, since min/max updated already
			return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);
		}
	}


    class Solution_iteration {

        LinkedList<TreeNode> queue = new LinkedList<>(); // store node, and its associated low/high in other two lists
        LinkedList<Integer> uppers = new LinkedList<>();
        LinkedList<Integer> lowers = new LinkedList<>();

        public void update(TreeNode root, Integer lower, Integer upper) {
            queue.add(root);
            lowers.add(lower);
            uppers.add(upper);
        }

        public boolean isValidBST(TreeNode root) {
            Integer lower = null;
            Integer upper = null;
            int val;
            update(root, lower, upper);

            while (!queue.isEmpty()) {
                root = queue.poll();
                lower = lowers.poll();
                upper = uppers.poll();

                if (root == null) continue;
                val = root.val;
                if (lower != null && val <= lower) return false;
                if (upper != null && val >= upper) return false;
                update(root.right, val, upper);
                update(root.left, lower, val);
            }
            return true;
        }
    }

}

All Problems

All Solutions