AlgoMaster Logo

Validate Binary Search Tree

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Inorder Traversal Recursively

Intuition:

A Binary Search Tree (BST) has the property that for each node, all the nodes in its left subtree have smaller values and all the nodes in its right subtree have larger values. Performing an inorder traversal of a BST should produce a sorted array of values. If the inorder traversal yields a sorted sequence without any repeated values, then the tree is a valid BST.

Steps:

  1. Perform an inorder traversal to check if each node value matches a sorted sequence.
  2. Use a helper function to perform the inorder traversal recursively.
  3. Keep track of the last seen value during the traversal to ensure that each current node's value is greater.

Code:

2. Inorder Traversal Iteratively

Intuition:

We can simulate the recursive inorder traversal using a stack to achieve an iterative solution. We push nodes to the stack while moving left, and then pop them to process each as we move right. This allows us to validate the BST properties without a recursive helper function.

Steps:

  1. Use a stack to simulate the inorder traversal.
  2. Push nodes onto the stack while traversing left.
  3. As nodes are popped from the stack, check the sequence order similar to the recursive approach.
  4. Store the last visited node value to validate the sorted order.

Code:

3. Recursive Valid Range

Intuition:

Instead of relying on inorder traversal, directly utilize the properties of a BST. For each node, determine a valid range it should lie within. The left child must be less than the current node and the right child greater. By passing down this valid range, you can recursively validate the entire tree.

Steps:

  1. Use a helper function to pass down the minimum and maximum allowable values for each node.
  2. Check if the current node's value lies within the valid range.
  3. Recursively check the left subtree with an updated max value and the right subtree with an updated min value.

Code: