-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrimaBinarySearchTree
36 lines (33 loc) · 1.01 KB
/
TrimaBinarySearchTree
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
32
33
34
35
36
/*************************************/
Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary search tree.
/*************************************/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode * trimBST(TreeNode * root, int L, int R) {
if (root == NULL) {
return NULL;
}
TreeNode *new_root = NULL;
if (root->val >= L && root->val <= R) {
new_root = root;
new_root->left = trimBST(root->left, L, R);
new_root->right = trimBST(root->right, L, R);
}
else if(root->val<L) {
new_root = trimBST(root->right,L,R);
}
else if (root->val > R) {
new_root = trimBST(root->left, L, R);
}
return new_root;
}
};