Problem Statement: Given the root of a binary search tree and the lowest and highest boundaries as low
and high
, trim the tree so that all its elements lies in [low, high]
. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant).
Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.
Example 1:
Output: [5,null,6,null,7]
Approach:
A simple DFS approach can be used to solve this problem. As we don't need to include those nodes whose value is out of the given range i.e low and high. When we get node.data < low
, we know that trimmed Binary tree must lie to the right of node and when we get node.data > high
, it means trimmed binary tree must occur to the left of node.
Code Implementation:
Output:
5 6 7
Complexity Analysis:
Time Complexity: O(n), where n is the number of nodes in tree.
Space Complexity:O(n), as we are using recursion hence extra stack space is used which can go upto number of nodes (n).
If you want to contribute such articles to solutions2coding.com please click here. Thank you!
If you want to contribute such articles to solutions2coding.com please click here. Thank you!