给定一个二叉搜索树,同时给定最小边界L 和最大边界 R。通过修剪二叉搜索树,使得所有节点的值在[L, R]中 (R>=L) 。你可能需要改变树的根节点,所以结果应当返回修剪好的二叉搜索树的新的根节点。
solution:

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 if(root == nullptr) return root;
14 if(root->val > R) return trimBST(root->left,L,R);
15 if(root->val < L) return trimBST(root->right,L,R);
16 root->left = trimBST(root->left,L,R);
17 root->right = trimBST(root->right,L,R);
18 return root;
19 }
20 };
思路:递归,对当前节点的数值进行分析,分为四种情况:
1.当前节点为空,返回当前节点
2.当前节点比R大,则其左孩子继续递归进行
3.当前节点比L小,则其右孩子继续递归进行
4.当前节点在[L,R]范围内,则左右孩子分别进行递归。
