来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/trim-a-binary-search-tree
题意:
给你二叉搜索树的根节点 root ,同时给定最小边界low 和最大边界 high。通过修剪二叉搜索树,使得所有节点的值在[low, high]中。修剪树 不应该 改变保留在树中的元素的相对结构 (即,如果没有被移除,原有的父代子代关系都应当保留)。 可以证明,存在 唯一的答案 。
所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。
示例 1:
输入:root = [1,0,2], low = 1, high = 2
输出:[1,null,2]
示例 2:
输入:root = [3,0,4,null,2,null,null,1], low = 1, high = 3
输出:[3,2,null,1]
提示:
树中节点数在范围 [1, 104] 内
0 <= Node.val <= 104
树中每个节点的值都是 唯一 的
题目数据保证输入是一棵有效的二叉搜索树
0 <= low <= high <= 104
参考文章
思路:
先说递归法的做法:
递归法,需要先确定递归方法的参数、返回值。在这道题中其实涉及到了二叉树重构的问题,所以借助递归方法返回节点的形式,可以简化代码。
递归法 Java代码:
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) return null;
if (root.val < low) return trimBST(root.right, low, high);
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;
}
}
下面是迭代法的思路:
首选我们将root调整为在范围中的节点,接着再分别对root的左右子树中不在范围内的节点进行剪切。
那么如何进行剪切呢?
如果是遍历到当前节点,对当前节点是否在范围内进行判断,如果不在范围内,则要舍弃当前节点,这样子做的话,需要记录当前节点的父节点(在别的题目中可能还要记录当前节点是父节点的左节点还是右节点),这样子做会比较麻烦。
那么我们干脆就对当前节点的儿子节点是否需要进行剪切进行判断,如果当前节点的儿子节点不在范围内,我们就直接使用儿子节点的儿子节点来替换当前节点的儿子节点(没想到说起来还有点绕)。这样子做,在剪切操作上就来的方便多了!
迭代法 Java代码:
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
//先调整root到范围内
while (root != null && (root.val < low || root.val > high)) {
if (root.val < low) root = root.right;
else root = root.left;
}
TreeNode cur = root;
//剪掉root左子树中不在范围内的节点
while (cur != null) {
while (cur.left != null && cur.left.val < low) cur.left = cur.left.right;
cur = cur.left;
}
cur = root;
//剪掉root右子树中不在范围内的节点
while (cur != null) {
while (cur.right != null && cur.right.val > high) cur.right = cur.right.left;
cur = cur.right;
}
return root;
}
}