题目:
解答:
思路:
令 trim(node) 作为该节点上的子树的理想答案。我们可以递归地构建该答案。
算法:
当node.val > R,那么修剪后的二叉树必定出现在节点的左边。
类似地,当node.val < L,那么修剪后的二叉树出现在节点的右边。否则,我们将会修剪树的两边。
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 { 14 if (root == NULL) 15 { 16 return root; 17 } 18 19 if (root->val > R) 20 { 21 return trimBST(root->left, L, R); 22 } 23 24 if (root->val < L) 25 { 26 return trimBST(root->right, L, R); 27 } 28 29 root->left = trimBST(root->left, L, R); 30 root->right = trimBST(root->right, L, R); 31 32 return root; 33 } 34 };