All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0601_0700.s0669_trim_a_binary_search_tree.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0601_0700.s0669_trim_a_binary_search_tree;

// #Medium #Depth_First_Search #Tree #Binary_Tree #Binary_Search_Tree
// #2022_03_22_Time_0_ms_(100.00%)_Space_45.7_MB_(24.17%)

import com_github_leetcode.TreeNode;

/*
 * 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;
 *     }
 * }
 */
/**
 * 669 - Trim a Binary Search Tree\.
 *
 * Medium
 *
 * 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.
 *
 * **Example 1:**
 *
 * ![](https://assets.leetcode.com/uploads/2020/09/09/trim1.jpg)
 *
 * **Input:** root = [1,0,2], low = 1, high = 2
 *
 * **Output:** [1,null,2]
 *
 * **Example 2:**
 *
 * ![](https://assets.leetcode.com/uploads/2020/09/09/trim2.jpg)
 *
 * **Input:** root = [3,0,4,null,2,null,null,1], low = 1, high = 3
 *
 * **Output:** [3,2,null,1]
 *
 * **Constraints:**
 *
 * *   The number of nodes in the tree in the range [1, 104].
 * *   0 <= Node.val <= 104
 * *   The value of each node in the tree is **unique**.
 * *   `root` is guaranteed to be a valid binary search tree.
 * *   0 <= low <= high <= 104
**/
public class Solution {
    public TreeNode trimBST(TreeNode root, int l, int r) {
        if (root == null) {
            return root;
        }
        if (root.val > r) {
            return trimBST(root.left, l, r);
        }
        if (root.val < l) {
            return trimBST(root.right, l, r);
        }
        root.left = trimBST(root.left, l, r);
        root.right = trimBST(root.right, l, r);
        return root;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy