Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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) {
- while (root != nullptr && (root->val < L || root->val > R)) {
- if (root->val < L) {
- root = root->right;
- }
- if (root->val > R) {
- root = root->left;
- }
- }
- if (root == nullptr) {
- return nullptr;
- }
- TreeNode* prev = root;
- TreeNode* temp = root->left;
- while (temp != nullptr) {
- if (temp->val < L) {
- prev->left = temp->right;
- temp = temp->right;
- }
- else {
- prev = temp;
- temp = temp->left;
- }
- }
- prev = root;
- temp = root->right;
- while (temp != nullptr) {
- if (temp->val > R) {
- prev->right = temp->left;
- temp = temp->left;
- }
- else {
- prev = temp;
- temp=temp->right;
- }
- }
- return root;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement