Skip to content

Commit 16e539b

Browse files
authored
Create trim-a-binary-search-tree.cpp
1 parent f8c8775 commit 16e539b

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

C++/trim-a-binary-search-tree.cpp

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
TreeNode* trimBST(TreeNode* root, int L, int R) {
16+
if (!root) {
17+
return nullptr;
18+
}
19+
if (root->val < L) {
20+
return trimBST(root->right, L, R);
21+
}
22+
if (root->val > R) {
23+
return trimBST(root->left, L, R);
24+
}
25+
root->left = trimBST(root->left, L, R);
26+
root->right = trimBST(root->right, L, R);
27+
return root;
28+
}
29+
};

0 commit comments

Comments
 (0)