AlgoMaster Logo

Trim a Binary Search Tree

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive DFS

Intuition:

The idea is to recursively traverse the tree and rebuild it by considering the constraints of a binary search tree (BST). For each node:

  • If the node's value is less than low, then discard the left subtree (because all values in the left subtree are also less than low) and trim the right subtree.
  • If the node's value is greater than high, discard the right subtree and trim the left subtree.
  • If the node's value is within the range [low, high], then keep the node and recursively trim both its left and right subtrees.

The base case for the recursion is when a null node is encountered.

Code:

2. Iterative DFS with Stack

Intuition:

This approach uses an iterative Depth-First Search (DFS) strategy with a stack to avoid the recursion overhead. The idea is the same as the recursive approach, but maintains a stack to process the nodes iteratively.

  • Initialize a stack and push the root node.
  • Pop elements from the stack, check if the current node is within the range, and adjust its children nodes accordingly.
  • Continue while the stack is not empty.

Code: