forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0662-maximum-width-of-binary-tree.kt
69 lines (57 loc) · 1.58 KB
/
0662-maximum-width-of-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
* }
*/
/*
* BFS solution
*/
class Solution {
fun widthOfBinaryTree(root: TreeNode?): Int {
root?: return 0
val q = ArrayDeque<Triple<TreeNode?, Int, Int>>()
var res = 0
var prevLevel = 0
var prevNum = 1
q.add(Triple(root, 1, 0))
while (q.isNotEmpty()) {
val (node, num, level) = q.poll()
if (level > prevLevel) {
prevLevel = level
prevNum = num
}
res = maxOf(res, num - prevNum + 1)
node?.left?.let {
q.add(Triple(node.left, 2 * num, level + 1))
}
node?.right?.let {
q.add(Triple(node.right, 2 * num + 1, level + 1))
}
}
return res
}
}
/*
* DFS solution
*/
class Solution {
fun widthOfBinaryTree(root: TreeNode?): Int {
var width = 0
val levelMap = HashMap<Int, Int>()
fun dfs(node: TreeNode?, depth: Int, pos: Int, levelMap: HashMap<Int, Int>) {
node?: return
if(!levelMap.contains(depth))
levelMap[depth] = pos
width = maxOf(width, (pos - levelMap[depth]!! + 1))
dfs(node.left, depth+1, 2*pos, levelMap)
dfs(node.right, depth+1, 2*pos+1, levelMap)
}
dfs(root, 0, 0, levelMap)
return width
}
}