[LeetCode] Split BST

776. Split BST

Given the root of a binary search tree (BST) and an integer target, split the tree into two subtrees where one subtree has nodes that are all smaller or equal to the target value, while the other subtree has all nodes that are greater than the target value. It Is not necessarily the case that the tree contains a node with the value target.

Additionally, most of the structure of the original tree should remain. Formally, for any child c with parent p in the original tree, if they are both in the same subtree after the split, then node c should still have the parent p.

Return an array of the two roots of the two subtrees.

  • Time : O(logn)
  • Space : O(logn)
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
27
28
29
30
31
/**
* 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 {
public:
vector<TreeNode *> splitBST(TreeNode *root, int target) {
vector<TreeNode *> res(2,NULL);
if(!root) return res;
if(root->val > target) {
res[1] = root;
auto child = splitBST(root->left, target);
root->left = child[1];
res[0] = child[0];
} else {
res[0] = root;
auto child = splitBST(root->right, target);
root->right = child[0];
res[1] = child[1];
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/19/PS/LeetCode/split-bst/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.