-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0742-closest-leaf-in-a-binary-tree.js
More file actions
58 lines (48 loc) · 1.57 KB
/
0742-closest-leaf-in-a-binary-tree.js
File metadata and controls
58 lines (48 loc) · 1.57 KB
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
52
53
54
55
56
57
58
/**
* Closest Leaf In A Binary Tree
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var findClosestLeaf = function (root, k) {
const treeAdjacencyList = new Map();
const allLeafValues = new Set();
function buildUndirectedGraph(currentNode, parentNode) {
if (!currentNode) {
return;
}
if (!currentNode.left && !currentNode.right) {
allLeafValues.add(currentNode.val);
}
if (parentNode) {
if (!treeAdjacencyList.has(currentNode.val)) {
treeAdjacencyList.set(currentNode.val, new Set());
}
if (!treeAdjacencyList.has(parentNode.val)) {
treeAdjacencyList.set(parentNode.val, new Set());
}
treeAdjacencyList.get(currentNode.val).add(parentNode.val);
treeAdjacencyList.get(parentNode.val).add(currentNode.val);
}
buildUndirectedGraph(currentNode.left, currentNode);
buildUndirectedGraph(currentNode.right, currentNode);
}
buildUndirectedGraph(root, null);
const bfsTraversalQueue = [k];
const nodesVisitedDuringBfs = new Set([k]);
while (bfsTraversalQueue.length > 0) {
const currentBfsNodeValue = bfsTraversalQueue.shift();
if (allLeafValues.has(currentBfsNodeValue)) {
return currentBfsNodeValue;
}
const nodeNeighbors = treeAdjacencyList.get(currentBfsNodeValue);
if (nodeNeighbors) {
for (const neighborNodeValue of nodeNeighbors) {
if (!nodesVisitedDuringBfs.has(neighborNodeValue)) {
nodesVisitedDuringBfs.add(neighborNodeValue);
bfsTraversalQueue.push(neighborNodeValue);
}
}
}
}
return -1;
};