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 5189612

Browse files
committedApr 4, 2025
Add solution #1110
1 parent 5cc668d commit 5189612

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed
 

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,139 LeetCode solutions in JavaScript
1+
# 1,140 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -883,6 +883,7 @@
883883
1106|[Parsing A Boolean Expression](./solutions/1106-parsing-a-boolean-expression.js)|Hard|
884884
1108|[Defanging an IP Address](./solutions/1108-defanging-an-ip-address.js)|Easy|
885885
1109|[Corporate Flight Bookings](./solutions/1109-corporate-flight-bookings.js)|Medium|
886+
1110|[Delete Nodes And Return Forest](./solutions/1110-delete-nodes-and-return-forest.js)|Medium|
886887
1122|[Relative Sort Array](./solutions/1122-relative-sort-array.js)|Easy|
887888
1123|[Lowest Common Ancestor of Deepest Leaves](./solutions/1123-lowest-common-ancestor-of-deepest-leaves.js)|Medium|
888889
1137|[N-th Tribonacci Number](./solutions/1137-n-th-tribonacci-number.js)|Easy|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 1110. Delete Nodes And Return Forest
3+
* https://leetcode.com/problems/delete-nodes-and-return-forest/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree, each node in the tree has a distinct value.
7+
*
8+
* After deleting all nodes with a value in toDelete, we are left with a forest (a disjoint
9+
* union of trees).
10+
*
11+
* Return the roots of the trees in the remaining forest. You may return the result in any order.
12+
*/
13+
14+
/**
15+
* Definition for a binary tree node.
16+
* function TreeNode(val, left, right) {
17+
* this.val = (val===undefined ? 0 : val)
18+
* this.left = (left===undefined ? null : left)
19+
* this.right = (right===undefined ? null : right)
20+
* }
21+
*/
22+
/**
23+
* @param {TreeNode} root
24+
* @param {number[]} toDelete
25+
* @return {TreeNode[]}
26+
*/
27+
var delNodes = function(root, toDelete) {
28+
const deleteSet = new Set(toDelete);
29+
const forest = [];
30+
31+
traverse(root, true);
32+
return forest;
33+
34+
function traverse(node, isRoot) {
35+
if (!node) return null;
36+
37+
const shouldDelete = deleteSet.has(node.val);
38+
if (isRoot && !shouldDelete) forest.push(node);
39+
40+
node.left = traverse(node.left, shouldDelete);
41+
node.right = traverse(node.right, shouldDelete);
42+
43+
return shouldDelete ? null : node;
44+
}
45+
};

0 commit comments

Comments
 (0)
Please sign in to comment.