669. Trim a Binary Search Tree 修剪二叉搜索树
解题思路:
总共分三种情况:
1) 如果根节点的值在[L,R]范围内,返回根节点,但是继续修剪根节点的左子树和右子树;
2)如果根节点的值小于L,由于二叉搜索树的性质,根节点的值和根节点的左子树的值肯定不在[L,R]范围内,这时候返回trim后的右子树;
3)如果根节点的值大于L,由于二叉搜索树的性质,根节点的值和根节点的右子树的值肯定不在[L,R]范围内,这时候返回trim后的左子树;
/**
* 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 == nullptr) {
return root;
}
if (root->val < L) return trimBST(root->right, L, R);
if (root->val > R) return trimBST(root->left, L, R);
// 这里表示root的值满足条件
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
}
};