-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdeleteNodesAndReturnForest.js
More file actions
51 lines (43 loc) · 1001 Bytes
/
deleteNodesAndReturnForest.js
File metadata and controls
51 lines (43 loc) · 1001 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number[]} to_delete
* @return {TreeNode[]}
*/
var delNodes = function(root, to_delete) {
let stack = [];
if (root === null) {
return [];
}
to_delete = new Set(to_delete);
let result = [];
let parent, current, branch;
stack.push([null, root, null]);
while (stack.length > 0) {
[parent, current, branch] = stack.pop();
if (parent === null) {
if (!to_delete.has(current.val)) {
result.push(current);
}
} else {
if (to_delete.has(current.val)) {
parent[branch] = null;
} else if (to_delete.has(parent.val)) {
result.push(current);
}
}
if (current.left) {
stack.push([current, current.left, "left"]);
}
if (current.right) {
stack.push([current, current.right, "right"]);
}
}
return result;
};