/**
* 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 root;
if (root->val >= low && root->val <= high) {
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
} else if (root->val > high) {
root = trimBST(root->left, low, high);
} else if (root->val < low) {
root = trimBST(root->right, low, high);
}
return root;
}
};
标签:修剪,right,TreeNode,val,随想录,二叉,low,root,left
From: https://www.cnblogs.com/huigugu/p/18680455