Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. TreeNode* trimBST(TreeNode* root, int L, int R) {
  13. while (root != nullptr && (root->val < L || root->val > R)) {
  14. if (root->val < L) {
  15. root = root->right;
  16. }
  17. if (root->val > R) {
  18. root = root->left;
  19. }
  20. }
  21.  
  22. if (root == nullptr) {
  23. return nullptr;
  24. }
  25.  
  26. TreeNode* prev = root;
  27. TreeNode* temp = root->left;
  28.  
  29. while (temp != nullptr) {
  30. if (temp->val < L) {
  31. prev->left = temp->right;
  32. temp = temp->right;
  33. }
  34. else {
  35. prev = temp;
  36. temp = temp->left;
  37. }
  38. }
  39.  
  40. prev = root;
  41. temp = root->right;
  42.  
  43.  
  44. while (temp != nullptr) {
  45. if (temp->val > R) {
  46. prev->right = temp->left;
  47. temp = temp->left;
  48. }
  49. else {
  50. prev = temp;
  51. temp=temp->right;
  52. }
  53. }
  54. return root;
  55. }
  56. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement