Recursive clean Java solution, 2ms


  • 0
    M

    This problem is similar to returning the different root-leaf paths in a binary tree. Solved it using pre-order recursion.

    public class Solution {
        public int sumNumbers(TreeNode root) {
            int totalSum = 0;
            StringBuilder sb = new StringBuilder();
            List<Integer> sums = new ArrayList<Integer>();
            getSumPaths(root, sb, sums);
            int size = sums.size();
            for( int i = 0; i < size; i++ )
                totalSum += sums.get(i);
            return totalSum;
        }
        
        private void getSumPaths(TreeNode root, StringBuilder sb, List<Integer> sums)
        {
            if( root == null )
                return;
            int length = sb.length();
            sb.append(root.val);
            if( root.left == null && root.right == null )
            {
                sums.add(Integer.parseInt(sb.toString()));
            }
            else
            {
                getSumPaths(root.left, sb, sums);
                getSumPaths(root.right, sb, sums);
            }
            sb.setLength(length);
        }
            
    }
    

Log in to reply
 

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