思路
- 何时只修剪左子树?——右子树全部超出范围,即根节点大于上界
- 何时只修剪右子树?——左子树全部超过范围,即根节点小于上界
- 何时共同修建左右子树?——根节点未超出范围,进行共同修建并连接
代码
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root==nullptr) return nullptr;
if(root->val >high)
return trimBST(root->left,low,high);
else if(root->val <low)
return trimBST(root->right,low,high);
else{
root->left=trimBST(root->left,low,high);
root->right=trimBST(root->right,low,high);
return root;
}
}
};
本文探讨了如何根据节点值与边界条件,仅修剪左子树、右子树或两者同时,通过C++代码详细展示了如何使用trimBST函数进行BST的修剪操作。关键在于理解范围限制与节点操作的时机。
314

被折叠的 条评论
为什么被折叠?



