1. 程式人生 > >leetcode669+保留BST中[L,R]間的節點值,遞迴

leetcode669+保留BST中[L,R]間的節點值,遞迴

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

/**
 * 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) {
        if(root==NULL) return NULL;
        if(L > root->val){
            return trimBST(root->right, L, R);
        }
        if(R < root->val){
            return trimBST(root->left, L, R);
        }
        if(L<=root->val && root->val <=R){
            root->left = trimBST(root->left, L, R);
            root->right = trimBST(root->right, L, R);
            return root;
        }
    }
};