|
| 1 | +/* |
| 2 | +Trim a Binary Search Tree |
| 3 | +========================= |
| 4 | +
|
| 5 | +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. |
| 6 | +
|
| 7 | +Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds. |
| 8 | +
|
| 9 | +Example 1: |
| 10 | +Input: root = [1,0,2], low = 1, high = 2 |
| 11 | +Output: [1,null,2] |
| 12 | +
|
| 13 | +Example 2: |
| 14 | +Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3 |
| 15 | +Output: [3,2,null,1] |
| 16 | +
|
| 17 | +Example 3: |
| 18 | +Input: root = [1], low = 1, high = 2 |
| 19 | +Output: [1] |
| 20 | +
|
| 21 | +Example 4: |
| 22 | +Input: root = [1,null,2], low = 1, high = 3 |
| 23 | +Output: [1,null,2] |
| 24 | +
|
| 25 | +Example 5: |
| 26 | +Input: root = [1,null,2], low = 2, high = 4 |
| 27 | +Output: [2] |
| 28 | +
|
| 29 | +Constraints: |
| 30 | +The number of nodes in the tree in the range [1, 104]. |
| 31 | +0 <= Node.val <= 104 |
| 32 | +The value of each node in the tree is unique. |
| 33 | +root is guaranteed to be a valid binary search tree. |
| 34 | +0 <= low <= high <= 104 |
| 35 | +*/ |
| 36 | + |
| 37 | +/** |
| 38 | + * Definition for a binary tree node. |
| 39 | + * struct TreeNode { |
| 40 | + * int val; |
| 41 | + * TreeNode *left; |
| 42 | + * TreeNode *right; |
| 43 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 44 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 45 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 46 | + * }; |
| 47 | + */ |
| 48 | + |
| 49 | +class Solution |
| 50 | +{ |
| 51 | +public: |
| 52 | + TreeNode *trimBST(TreeNode *root, int low, int high) |
| 53 | + { |
| 54 | + if (!root) |
| 55 | + return root; |
| 56 | + |
| 57 | + auto left = trimBST(root->left, low, high); |
| 58 | + auto right = trimBST(root->right, low, high); |
| 59 | + |
| 60 | + root->left = left; |
| 61 | + root->right = right; |
| 62 | + |
| 63 | + if (root->val < low) |
| 64 | + return right; |
| 65 | + else if (root->val > high) |
| 66 | + return left; |
| 67 | + |
| 68 | + return root; |
| 69 | + } |
| 70 | +}; |
0 commit comments