Leetcode 669: Trim a Binary Search Tree

grid47
grid47
Exploring patterns and algorithms
Sep 1, 2024 5 min read

A binary search tree where the tree is trimmed to fit a given range, with each trimmed node softly glowing.
Solution to LeetCode 669: Trim a Binary Search Tree Problem

You are given the root of a binary search tree (BST) and two integer values low and high. Trim the tree such that all its elements lie within the inclusive range [low, high]. The tree’s relative structure should remain unchanged, and the root may change depending on the given bounds.
Problem
Approach
Steps
Complexity
Input: The input consists of the root of a binary search tree and two integer values `low` and `high`, representing the boundaries within which all elements of the tree should lie.
Example: root = [4,2,6,1,3,5,7], low = 3, high = 6
Constraints:
• 1 <= Number of nodes <= 10^4
• 0 <= Node.val <= 10^4
• low <= high <= 10^4
Output: Return the root of the trimmed binary search tree. The structure of the tree must remain intact, with nodes lying within the range `[low, high]`.
Example: [4,3,6,null,null,5]
Constraints:
• The output tree must have the same structure as the input tree, but with only the nodes that fall within the specified range.
Goal: Trim the binary search tree by removing nodes that fall outside the range [low, high]. The relative structure of the tree should be maintained.
Steps:
• 1. Check if the current node’s value is less than low, in which case we only need to trim the right subtree.
• 2. If the current node’s value is greater than high, trim the left subtree.
• 3. If the current node's value lies within the range [low, high], recursively trim both the left and right subtrees.
Goal: The problem has constraints related to the tree structure and values.
Steps:
• 1 <= Number of nodes <= 10^4
• Node values are unique and within the range [0, 10^4].
Assumptions:
• The binary search tree is valid and follows the properties of a BST.
• The node values are unique, ensuring there is only one possible valid trimming of the tree.
Input: root = [4,2,6,1,3,5,7], low = 3, high = 6
Explanation: After trimming, the tree only contains nodes with values between 3 and 6. The final tree is [4,3,6,null,null,5].

Input: root = [10,5,15,3,7,null,18], low = 5, high = 15
Explanation: After trimming, the tree contains nodes with values between 5 and 15. The final tree is [10,5,null,null,7].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus