2022-07-14 00:13:48 +02:00
|
|
|
/**
|
|
|
|
* 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 fun levelOrder(root: TreeNode?, levels: MutableList<MutableList<Int>>, level: Int): MutableList<MutableList<Int>> {
|
|
|
|
if (root == null) {
|
|
|
|
return levels
|
|
|
|
}
|
2023-06-02 17:19:02 +02:00
|
|
|
|
2022-07-14 00:13:48 +02:00
|
|
|
if (level + 1 > levels.size) {
|
|
|
|
levels.add(mutableListOf<Int>())
|
|
|
|
}
|
2023-06-02 17:19:02 +02:00
|
|
|
|
2022-07-14 00:13:48 +02:00
|
|
|
levels[level].add(root.`val`)
|
|
|
|
levelOrder(root.left, levels, level + 1)
|
|
|
|
return levelOrder(root.right, levels, level + 1)
|
|
|
|
}
|
2023-06-02 17:19:02 +02:00
|
|
|
|
2022-07-14 00:13:48 +02:00
|
|
|
fun levelOrder(root: TreeNode?): List<List<Int>> = levelOrder(root, mutableListOf<MutableList<Int>>(), 0)
|
|
|
|
}
|