Sum of Root to Leaf Binary Numbers

I solved this problem initially using Java but here’s a similar implementation using Kotlin.

/**
 * 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 sumRootToLeaf(root: TreeNode?): Int {
        var sum = 0
        val stack = Stack<TreeNode>()
        fun sumRootToLeaf_(node: TreeNode?, stack: Stack<TreeNode>){
            if(node == null) return
            
            stack.push(node)
            sumRootToLeaf_(node.left, stack)
            sumRootToLeaf_(node.right, stack)
            
            if(node.left == null && node.right == null){
                sum += Integer.parseInt(stack.map {it.`val`}.joinToString(""),2)
            }
            
            stack.pop()            
        }
        
        sumRootToLeaf_(root, stack)
        
        return sum
    }
}
Runtime: 192 ms, faster than 20.83% of Kotlin online submissions for Sum of Root To Leaf Binary Numbers.
Memory Usage: 35.9 MB, less than 100.00% of Kotlin online submissions for Sum of Root To Leaf Binary Numbers.
comments powered by Disqus