TreeNode* trimBST(TreeNode* root, int L, int R) {
        if (!root) {
          return root;
        }
	//for the nodes which are outside L,R, remove them from the tree
        if (root->val < L) return trimBST(root->right,L,R);
        if (root->val > R) return trimBST(root->left,L,R);
	//for the nodes inside L,R modify their left and right values to be inside L,R
        root->left = trimBST(root->left,L,R);
        root->right = trimBST(root->right,L,R);
        return root;
    }
Exemple #2
0
 TreeNode* trimBST(TreeNode* root, int L, int R) {
     if(root == NULL)
         return NULL;
     
     if(root->val < L)
         return trimBST(root->right, L, R); 
     else if(root->val > R)
         return trimBST(root->left, L, R);
         
     root->left = trimBST(root->left, L, root->val);
     root->right = trimBST(root->right, root->val, R);
     return root;
 }
 TreeNode* trimBST(TreeNode* root, int L, int R) {
     if (!root) {
         return nullptr;
     }
     if (root->val < L) {
         return trimBST(root->right, L, R);
     }
     if (root->val > R) {
         return trimBST(root->left, L, R);
     }
     root->left = trimBST(root->left, L, R);
     root->right = trimBST(root->right, L, R);
     return root;
 }