Skip to content

Commit 416492f

Browse files
committed
1 parent 3a01b68 commit 416492f

File tree

1 file changed

+60
-0
lines changed
  • src/main/kotlin/leetcode/maximum-width-of-binary-tree

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package leetcode.`maximum-width-of-binary-tree`
2+
3+
import TreeNode
4+
import org.junit.Test
5+
import java.util.LinkedList
6+
import kotlin.math.abs
7+
8+
class Solution {
9+
fun widthOfBinaryTree(root: TreeNode?): Int {
10+
root ?: return 0
11+
val queue = LinkedList<PostionTreeNode>()
12+
var currentDep = 0
13+
var maxWidth = 1
14+
var f: Int? = null
15+
queue.push(PostionTreeNode(root, 0, 1))
16+
while (queue.isNotEmpty()) {
17+
val k = queue.poll() as PostionTreeNode
18+
if (currentDep != k.depth) {
19+
currentDep = k.depth
20+
f = k.postion
21+
} else {
22+
if (f == null) {
23+
f = k.postion
24+
}
25+
maxWidth = Math.max(maxWidth, k.postion - f + 1)
26+
}
27+
if (k.node.left != null) {
28+
queue.offer(PostionTreeNode(k.node.left!!, k.postion * 2, k.depth+1))
29+
}
30+
if (k.node.right != null) {
31+
queue.offer(PostionTreeNode(k.node.right!!, k.postion * 2 + 1, k.depth+1))
32+
}
33+
}
34+
return maxWidth
35+
}
36+
37+
class PostionTreeNode(val node: TreeNode, val postion: Int, val depth: Int)
38+
39+
@Test
40+
fun test() {
41+
// [1,3,2,5,null,null,9,6,null,7]
42+
val root = TreeNode(1)
43+
val node1 = TreeNode(3)
44+
val node2 = TreeNode(2)
45+
val node3 = TreeNode(5)
46+
val node4 = TreeNode(5)
47+
val node5 = TreeNode(5)
48+
val node6 = TreeNode(5)
49+
50+
root.left = node1
51+
root.right = node2
52+
53+
node1.left = node3
54+
node3.left = node4
55+
56+
node2.right = node5
57+
node5.left = node6
58+
widthOfBinaryTree(root)
59+
}
60+
}

0 commit comments

Comments
 (0)