mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
problems: add binary tree level-order traversal
This commit is contained in:
parent
671fe591f6
commit
7929858e64
1 changed files with 27 additions and 0 deletions
27
problems/binary-tree-level-order-traversal.kt
Normal file
27
problems/binary-tree-level-order-traversal.kt
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
}
|
||||||
|
|
||||||
|
if (level + 1 > levels.size) {
|
||||||
|
levels.add(mutableListOf<Int>())
|
||||||
|
}
|
||||||
|
|
||||||
|
levels[level].add(root.`val`)
|
||||||
|
levelOrder(root.left, levels, level + 1)
|
||||||
|
return levelOrder(root.right, levels, level + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun levelOrder(root: TreeNode?): List<List<Int>> = levelOrder(root, mutableListOf<MutableList<Int>>(), 0)
|
||||||
|
}
|
Loading…
Reference in a new issue