现在对递归算法的理解就是返回的是对当前点的处理结果。如果左边不行就返回对右子树处理的结果,如果右边不行就返回对左子树处理的结果,如果两边都可以就对左右分别处理,再返回该节点。
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root == nullptr) return nullptr;
if(root->val < low) {
return trimBST(root->right, low, high);
} else if(root->val > high) {
return trimBST(root->left, low, high);
} else {
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
}
这篇博客探讨了如何使用递归算法来修剪二叉搜索树(BST),确保所有节点值在给定的low和high范围内。通过比较节点值与范围边界,递归地处理左子树、右子树,最终得到一个修剪后的BST。在处理过程中,如果节点值小于low,则返回右子树的结果;如果大于high,则返回左子树的结果;否则保留节点并继续修剪其子树。

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



