A very simple Java solution

  • 0

    The solution is based on DFS and calculate accumulated value during recursion.

    public class Solution {
        public int sumNumbers(TreeNode root) {
            return helper(root,0);
        public int helper(TreeNode node, int number) {
            if(node == null) return 0;
            if(node.left == null && node.right == null) return number*10+node.val; 
            else return helper(node.left,number*10+node.val)+helper(node.right,number*10+node.val);

Log in to reply

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