本题一种经典错误就是在带返回值的递归函数中,遇到在范围外的结点就直接返回 NULL,实际上这种策略在官方给出的示例 2 中就是错误的。
正确的策略应为:遇到小于范围内的结点,递归修剪该结点的右子树(因为右子树可能会落在范围内);同理遇到大于范围内的结点,递归修剪该结点的左子树;若结点值落在范围内,则递归修剪左右节点并更新左右结点的值。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root == NULL) // 遇到空结点不用修剪,返回空
return NULL;
if(root->val < low) // 遇到小于范围内的结点,递归修剪该结点的右子树,返回结果供上层拼接
return trimBST(root->right, low, high);
if(root->val > high) // 遇到大于范围内的结点,递归修剪该结点的左子树,返回结果供上层拼接
return trimBST(root->left, low, high);
// 结点值落在范围内,则递归修剪左右节点并更新(拼接)左右结点的值
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
};