https://leetcode.com/problems/trim-a-binary-search-tree/

1. Use recursion:

  1. //24 ms 12.9 MB
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. TreeNode* trimBST(TreeNode* root, int L, int R) {
  14. if(!root) return NULL;
  15. root->left = trimBST(root->left, L, R);
  16. root->right = trimBST(root->right, L, R);
  17. if(root->val < L || root->val > R){
  18. if(root->left)
  19. root = root->left;
  20. else if(root->right)
  21. root = root->right;
  22. else
  23. root = NULL;
  24. }
  25. return root;
  26. }
  27. };