#669 Trim a Binary Search Tree

Description

Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node’s descendant should remain a descendant). It can be proven that there is a unique answer.

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

Examples

Example 1:

在这里插入图片描述

Input: root = [1,0,2], low = 1, high = 2
Output: [1,null,2]

Example 2:
在这里插入图片描述

Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
Output: [3,2,null,1]

Example 3:

Input: root = [1], low = 1, high = 2
Output: [1]

Example 4:

Input: root = [1,null,2], low = 1, high = 3
Output: [1,null,2]

Example 5:

Input: root = [1,null,2], low = 2, high = 4
Output: [2]

Constraints:

The number of nodes in the tree in the range [1, 104].
0 <= Node.val <= 1 0 4 10^4 104
The value of each node in the tree is unique.
root is guaranteed to be a valid binary search tree.
0 <= low <= high <= 1 0 4 10^4 104

思路

这题是删除所有不在规定区间内的二叉搜索树节点,并保留原格式
这道题虽然是删除操作,但也可以认为是构造过程,因此不用对当前节点的左右孩子做分别判断。

首先提一下二叉搜索树的默认规则:

  • 左边永远小于右边

因此判断的时候

  • 如果currNode.val < low
    那么可能满足区间的节点一定出现在currNode.right中,所以逐步将currNode向右移直到找到这个节点或者到null为止
  • 如果currNode.val > high
    那么可能满足区间的节点一定出现在currNode.left中,所以逐步将currNode向左移直到找到这个节点或者到null为止

整个流程就可以变为:

  • 首先找到第一个在区间内的节点作为根节点
  • 对该节点的左右孩子分别找到在区间内的节点

说的可能不是很清楚,看代码比较简洁易懂

代码

/**
 * 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) {
        while (root != null && (root.val < low || root.val > high)){
            if (root.val < low)
                root = root.right;
            else
                root = root.left;
        }
        
        if(root == null)
            return null;
        
        root.right = trimBST(root.right, low, high);
        root.left = trimBST(root.left, low, high);
        
        return root;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值