Skip to content

Commit 647fa31

Browse files
committed
no message
1 parent 3837592 commit 647fa31

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import Foundation
2+
3+
class Solution {
4+
func findClosestLeaf(_ root: TreeNode?, _ k: Int) -> Int {
5+
var graph = [Int:[Int]](), queue = [(TreeNode?, TreeNode)]() // (currentNode, parentNode)
6+
queue.append((root, TreeNode(Int.max)))
7+
8+
// Creates the graph.
9+
while !queue.isEmpty {
10+
let (node, parentNode) = queue.removeFirst()
11+
if let node = node {
12+
graph[node.val, default: [Int]()].append(parentNode.val)
13+
graph[parentNode.val, default: [Int]()].append(node.val)
14+
queue.append((node.left, node))
15+
queue.append((node.right, node))
16+
}
17+
}
18+
19+
var valQueue = [Int](), visited = Set<Int>()
20+
valQueue.append(k)
21+
while !valQueue.isEmpty {
22+
let currentNodeVal = valQueue.removeFirst()
23+
visited.insert(currentNodeVal)
24+
if let neighbours = graph[currentNodeVal] {
25+
if neighbours.count <= 1 && currentNodeVal != Int.max {
26+
return currentNodeVal
27+
}
28+
for i in 0..<neighbours.count {
29+
let neighbour = neighbours[i]
30+
if !visited.contains(neighbour) {
31+
valQueue.append(neighbour)
32+
}
33+
}
34+
} else {
35+
return currentNodeVal
36+
}
37+
}
38+
return -1
39+
}
40+
}

0 commit comments

Comments
 (0)