[LeetCode] Trim a Binary Search Tree

669. Trim a Binary Search Tree

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). It can be proven that there is a unique answer.

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
TreeNode* helper(TreeNode* node, int& l, int& r) {
if(!node) return nullptr;
if(l <= node->val and node->val <= r) {
node->left = helper(node->left, l, r);
node->right = helper(node->right, l, r);
return node;
} else if(l > node->val) return helper(node->right, l, r);
else return helper(node->left, l, r);
}
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
return helper(root, low, high);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/15/PS/LeetCode/trim-a-binary-search-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.