Can anyone point out the error, giving expected answer on my machine


  • 0
    A

    I am appending all the values to a string and when reached a leaf add it to a arraylist. at the end add all numbers in the arraylist. for input {0,1} on my machine it gives sum as zero, oj says output is 10, I don't know how. I wrote another solution which was accepted and all answers with this and accepted solution are same on my machine.
    Also evaluate my the approach.

     public int sumNumbers(TreeNode root) {
                findRootToLeafSum( root,""); 
               int sum = 0;
        		for (String asd : as) {
        			sum = sum + Integer.parseInt(asd);
        		}
        		return sum;
        }
        static ArrayList<String> as = new ArrayList<String>();
        public static void findRootToLeafSum(TreeNode root, String path) {
        		if (root == null)
        			return;
        		if (root.left == null && root.right == null) {
        			path = path + root.val;
        			as.add(path);
        			return;
        		}
        		path = path + root.val;
        		findRootToLeafSum(root.left, path);
        		findRootToLeafSum(root.right, path);
        	}

Log in to reply
 

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