-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind Distance in a Binary Tree.kt
69 lines (56 loc) · 1.85 KB
/
Find Distance in a Binary Tree.kt
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
59
60
61
62
63
64
65
66
67
68
69
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
private val graph: MutableMap<Int, MutableList<Int>> = mutableMapOf()
private val visited: MutableMap<Int, Int> = mutableMapOf()
fun findDistance(root: TreeNode?, p: Int, q: Int): Int {
generateGraph(root)
val graphQueue: Queue<Int> = LinkedList<Int>()
graphQueue.add(p)
visited[p] = 0
while (graphQueue.isNotEmpty()) {
val top = graphQueue.poll()
val visitedValue = visited[top] ?: 0
if (top == q) {
return visitedValue
}
val neighbors = graph[top].orEmpty()
for (neighbor in neighbors) {
if (!visited.contains(neighbor)) {
visited[neighbor] = visitedValue + 1
graphQueue.add(neighbor)
}
}
}
return -1
}
private fun generateGraph(root: TreeNode?) {
if (root == null) {
return
}
val rootValue = root?.`val`
val rootNeighbors = graph.getOrPut(rootValue) { mutableListOf() }
if (root?.left != null) {
val leftValue = root?.left?.`val` ?: 0
rootNeighbors.add(leftValue)
val leftNeighbors = graph.getOrPut(leftValue) { mutableListOf() }
leftNeighbors.add(rootValue)
}
if (root?.right != null) {
val rightValue = root?.right?.`val` ?: 0
rootNeighbors.add(rightValue)
val rightNeighbors = graph.getOrPut(rightValue) { mutableListOf() }
rightNeighbors.add(rootValue)
}
generateGraph(root?.left)
generateGraph(root?.right)
}
}