本题细节很多,需要重新回顾代码随想录-修剪二叉搜索树,代码如下:
/**
* 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 null;
//当前值小于最小值,那么把左子树全部删除,返回右子树
//这其中包含着修剪子树的操作,看代码随想录相关.
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;
}
}
}