669. 修剪二叉搜索树(难度:中等)

题目链接:https://leetcode.cn/problems/trim-a-binary-search-tree/

题目描述:

给你二叉搜索树的根节点 root ,同时给定最小边界low 和最大边界 high。通过修剪二叉搜索树,使得所有节点的值在[low, high]中。修剪树 不应该 改变保留在树中的元素的相对结构 (即,如果没有被移除,原有的父代子代关系都应当保留)。 可以证明,存在 唯一的答案

所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。

示例 1:

img

输入:root = [1,0,2], low = 1, high = 2
输出:[1,null,2]

示例 2:

img

输入: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

解法:深度优先遍历

还是一句话,二叉树先考虑递归算法。。。

这道题也是一个经典的递归算法,通过题目描述,一共是如下几种情况:

  • 当 root.val < low,剪掉root.left。
  • 当 root.val > high,剪掉 root.right。
  • 当 root.left.val < low,root.left = root.left.right;
  • 当 root.right.val > high,root.right = root.right.left;

代码:

/**
 * 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) {
        root = dfs(root,low,high);
        return root;
    }

    public TreeNode dfs(TreeNode root, int low, int high) {
        while(root != null) {
            if(root.val < low) {
                root = root.right;
            } else if(root.val > high) {
                root = root.left;
            } else {
                break;
            }
        }
        if(root == null) {
            return root;
        }

        if(root.left != null && root.left.val < low) {
            root.left = root.left.right;
        }

        if(root.right != null && root.right.val > high) {
            root.right = root.right.left;
        }

        root.left = dfs(root.left,low,high);
        root.right = dfs(root.right,low,high);
        return root;
    }
}

image-20220910222536782

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值