Binary Tree Level Order Traversal II

The solution for this problem is the same as the other similarly named problem. Except at the end, we just have to reverse the list before returning it.

/**
 * 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
 * }
 */

import java.util.*

class Solution {
    fun levelOrderBottom(root: TreeNode?): List<List<Int>> {
        if(root == null) return emptyList<List<Int>>()
        val queue = LinkedList<TreeNode>()
        val level = LinkedList<Int>()
        
        val output = ArrayList<ArrayList<Int>>()
        
        queue.offer(root)
        level.offer(0)
        
        while(queue.isNotEmpty()){
            val node = queue.poll()
            val currentLevel = level.poll()
            
            if(currentLevel == output.size){
                output.add(ArrayList<Int>())
            }
            
            output[currentLevel].add(node?.`val`!!)
            
            if(node?.left != null) {
                queue.add(node?.left)
                level.offer(currentLevel + 1)
            }
            if(node?.right != null) {
                queue.add(node?.right)
                level.offer(currentLevel + 1)
            }
        }
        
        return output.reversed()
    }
}
Runtime: 200 ms, faster than 42.86% of Kotlin online submissions for Binary Tree Level Order Traversal II.
Memory Usage: 35.7 MB, less than 100.00% of Kotlin online submissions for Binary Tree Level Order Traversal II.
comments powered by Disqus