Solution in less than 10 lines


  • 0

    Simply using Depth-first search, code in 10 lines, runtime 136ms

    var sumNumbers = function(root) {
        function DFS(root, sumOfPath) {
            if (!root) return 0; //return 0 when node doesn't exists
            sumOfPath = 10 * sumOfPath + root.val; // sum of current path (till this node)
            if (!root.left && !root.right) return sumOfPath; //return on leaf node
            return DFS(root.left, sumOfPath) + DFS(root.right, sumOfPath); //keep on calculating
        }
        return DFS(root, 0);
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.