一、题目
二、代码
/**
* 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
{
//下界左边一定不满足
//上界右边一定不满足
//找到就返回 找不到返回null
public TreeNode build_tree_low(TreeNode pro ,int low )
{
if(pro.val>=low) return pro;
TreeNode re_node = new TreeNode(0);
re_node = null;
if(pro.val<low&& pro.right!=null)
{
re_node = build_tree_low(pro.right,low);
}
if(pro.val>low&& pro.left!=null)
{
re_node = build_tree_low(pro.left,low);
}
return re_node;
}
//找到就返回 找不到返回null
public TreeNode build_tree_high(TreeNode pro, int high)
{
if(pro.val<=high) return pro;
TreeNode re_node = new TreeNode(0);
re_node = null;
if(pro.val>high&&pro.left!=null) re_node = build_tree_high(pro.left,high);
if(pro.val<high&&pro.right!=null) re_node = build_tree_high(pro.right,high);
return re_node;
}
public void recursion(TreeNode pro, int low, int high)
{
if(pro.left!= null &&pro.val>low) recursion(pro.left,low,high);
//左侧小于下界 开始剪枝操作
if(pro.left!=null && pro.left.val < low)
{
TreeNode temp_node = pro.left;
pro.left =null;
pro.left = build_tree_low(temp_node,low);
//找左侧的子右侧节点,替换左侧节点
}
//右侧大于上界 开始剪枝
if(pro.right!=null && pro.right.val > high)
{
//找到右侧的子左侧节点,替换右节点
TreeNode temp_node = pro.right;
pro.right =null;
pro.right = build_tree_high(temp_node,high);
}
if(pro.right!=null &&pro.val<high) recursion(pro.right,low,high);
}
TreeNode new_root = new TreeNode(0);
boolean stop_flag = false;
public void recursion_root(TreeNode root, int low, int high)
{
if(stop_flag==true) return;
if(root.val>=low&&root.val<=high)
{
new_root = root;
stop_flag = true;
}
if(root.val>high&&root.left!=null) recursion_root(root.left,low,high);
if(root.val<low&&root.right!=null) recursion_root(root.right,low,high);
}
public TreeNode trimBST(TreeNode root, int low, int high)
{
if(root == null) return null;
//第一步 让root在范围之中
new_root = null;
recursion_root(root,low,high);
root = new_root;
if(root==null) return null;
recursion(root,low,high);
return 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 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;
}
}