1.题目描述:
给你二叉搜索树的根节点root,同时给定最小边界low和最大边界high。通过修剪二叉搜索树,使得所有节点的值在[low,high]中。修剪树不应该改变保留在树中的元素的相对结构。可以证明,存在唯一的答案。所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。
2.递归:
leetcode701. 二叉搜索树中的插入操作、leetcode450. 删除二叉搜索树中的节点和本题三者的递归都返回了处理完的当前root节点作为上级递归的左右子树,可以参考来看。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) return root;
if (root.val < low) return trimBST(root.right, low, high);//左子树全剪,返回修剪后的右子树root节点
else if (root.val > high) return trimBST(root.left, low, high);//右子树全剪,返回修剪后的左子树root节点
else {
root.left = trimBST(root.left, low, high);//当前节点在范围内,则递归修建左右子树并相连
root.right = trimBST(root.right, low, high);
}
return root;
}
}
二刷:
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) return root;
if (root.val > high) return trimBST(root.left, low, high);
if (root.val < low) return trimBST(root.right, low, high);
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
}
3.迭代:
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) return root;
while((root != null) && (root.val > high || root.val < low)) {//处理头节点使其位于[low,high]区间
root = root.val > high ? root.left : root.right;
}
TreeNode temp = root;
while (temp != null) {//迭代处理root左子树,修剪所有小于low的节点(左子树所有节点不会大于high)
while (temp.left != null && temp.left.val < low) temp.left = temp.left.right;
temp = temp.left;
}
temp = root;
while (temp != null) {//迭代处理root右子树,修剪所有大于high的节点(右子树所有节点不会小于low)
while (temp.right != null && temp.right.val > high) temp.right = temp.right.left;
temp = temp.right;
}
return root;
}
}