Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit f721137

Browse files
committedMar 9, 2025
Add solution #669
1 parent 3669d7a commit f721137

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,7 @@
502502
664|[Strange Printer](./0664-strange-printer.js)|Hard|
503503
667|[Beautiful Arrangement II](./0667-beautiful-arrangement-ii.js)|Medium|
504504
668|[Kth Smallest Number in Multiplication Table](./0668-kth-smallest-number-in-multiplication-table.js)|Hard|
505+
669|[Trim a Binary Search Tree](./0669-trim-a-binary-search-tree.js)|Medium|
505506
670|[Maximum Swap](./0670-maximum-swap.js)|Medium|
506507
680|[Valid Palindrome II](./0680-valid-palindrome-ii.js)|Easy|
507508
684|[Redundant Connection](./0684-redundant-connection.js)|Medium|
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 669. Trim a Binary Search Tree
3+
* https://leetcode.com/problems/trim-a-binary-search-tree/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary search tree and the lowest and highest boundaries as low and high,
7+
* trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change
8+
* the relative structure of the elements that will remain in the tree (i.e., any node's descendant
9+
* should remain a descendant). It can be proven that there is a unique answer.
10+
*
11+
* Return the root of the trimmed binary search tree. Note that the root may change depending on
12+
* the given bounds.
13+
*/
14+
15+
/**
16+
* Definition for a binary tree node.
17+
* function TreeNode(val, left, right) {
18+
* this.val = (val===undefined ? 0 : val)
19+
* this.left = (left===undefined ? null : left)
20+
* this.right = (right===undefined ? null : right)
21+
* }
22+
*/
23+
/**
24+
* @param {TreeNode} root
25+
* @param {number} low
26+
* @param {number} high
27+
* @return {TreeNode}
28+
*/
29+
var trimBST = function(root, low, high) {
30+
if (!root) return null;
31+
32+
if (root.val < low) return trimBST(root.right, low, high);
33+
if (root.val > high) return trimBST(root.left, low, high);
34+
root.left = trimBST(root.left, low, high);
35+
root.right = trimBST(root.right, low, high);
36+
37+
return root;
38+
};

0 commit comments

Comments
 (0)
Please sign in to comment.