- 对于递归的写法除了大写的服字,无话可说
- 由于是修剪二叉树,所以会有明确的方向性
- 当某一结点小于最小值,说明其左子树全部要修剪掉
- 当某一结点大于最大值,说明其右子树全部要修剪掉
#include <iostream>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(): val(0), left(nullptr), right(nullptr) {}
TreeNode(int v): val(v), left(nullptr), right(nullptr) {}
TreeNode(int v, TreeNode* l, TreeNode* r): val(v), left(l), right(r) {}
};
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == nullptr)
return nullptr;
else if (root->val < low)
return trimBST(root->right, low, high);
else 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;
}
};
int main()
{
Solution s;
return 0;
}