Skip to content

Commit fee3fcb

Browse files
Merge pull request #220
add new problem 24.09
2 parents 20401ca + 6a0610a commit fee3fcb

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

contest/src/main/java/com/github/contest/binaryTree/BinaryTreeLeetcode.kt

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,3 +305,51 @@ private fun isSameTree(root: TreeNode?, subRoot: TreeNode?): Boolean {
305305

306306
return isSameTree(root?.left, subRoot?.left) && isSameTree(root?.right, subRoot?.right)
307307
}
308+
309+
310+
/**
311+
* 655. Print Binary Tree
312+
*/
313+
314+
fun printTree(root: TreeNode?): List<List<String>> {
315+
root ?: return listOf()
316+
317+
val rows = height(root)
318+
val col = (1 shl rows) - 1
319+
val res = MutableList(rows) { _ ->
320+
MutableList(col) { "" }
321+
}
322+
val rootPos = (col - 1) / 2
323+
val queue = LinkedList<Triple<TreeNode, Int, Int>>().apply {
324+
val triple = Triple(root, 0, rootPos)
325+
offer(triple)
326+
}
327+
328+
while (queue.isNotEmpty()) {
329+
val size = queue.size
330+
331+
for (i in 0 until size) {
332+
val (node, level, col) = queue.poll()
333+
val offset = 1 shl (rows - level - 2)
334+
335+
res[level][col] = node.`val`.toString()
336+
337+
node.left?.let {
338+
val triple = Triple(it, level + 1, col - offset)
339+
queue.offer(triple)
340+
}
341+
342+
node.right?.let {
343+
val triple = Triple(it, level + 1, col + offset)
344+
queue.offer(triple)
345+
}
346+
}
347+
}
348+
349+
return res
350+
}
351+
352+
private fun height(root: TreeNode?): Int = when {
353+
root == null -> 0
354+
else -> 1 + maxOf(height(root.left), height(root.right))
355+
}

0 commit comments

Comments
 (0)