给定一个二叉搜索树,同时给定最小边界L 和最大边界 R。通过修剪二叉搜索树,使得所有节点的值在[L, R]中 (R>=L) 。你可能需要改变树的根节点,所以结果应当返回修剪好的二叉搜索树的新的根节点。
示例 1:
输入: 1 / \ 0 2 L = 1 R = 2 输出: 1 \ 2
示例 2:
输入: 3 / \ 0 4 \ 2 / 1 L = 1 R = 3 输出: 3 / 2 / 1
思路:
这道题借鉴了discuss部分,自己没想出来,主要是不知道怎么删除节点和拼接满足要求的节点。
伪代码叙述如下:
If the root value in the range [L, R]
we need return the root, but trim its left and right subtree;
else if the root value < L
because of binary search tree property, the root and the left subtree are not in range;
we need return trimmed right subtree.
else
similarly we need return trimmed left subtree.并且给出了不释放空间的代码:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if (root == NULL) return NULL;
if (root->val < L) return trimBST(root->right, L, R);
if (root->val > R) return trimBST(root->left, L, R);
root->left = trimBST(root->left, L, R);
root->right = trimBST(root->right, L, R);
return root;
}这里的拼接体现在,如下图的树:Input: 3 / \ 0 4 \ 2 / 1 L = 1 R = 3 Output: 3 / 2 / 1
1:当前节点为3,正好在范围内,修建左右子树
2:0为3的左节点,由于小于L,所以返回0->right,当0->right子树修改完成后,便拼接到0这个节点,这时3->left的节点便是0->right的修改树结构,从而实现拼接。
修剪二叉搜索树
本文介绍了一种修剪二叉搜索树的方法,使所有节点值位于指定范围内。通过递归修剪不符合条件的节点,并重新连接剩余节点,最终返回修剪后的根节点。
508

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



