My java solution for reference


  • 0
    R
    public int sumNumbers(TreeNode root) {
    if(root==null){
    	return 0;
    }
    if(root.left==null&&root.right==null){
    	return root.val;
    }
    ArrayList<ArrayList<String>> list = DFS(root);
    int sum=0;
    for(ArrayList<String> l:list){
    	String num = "";
    	for(String s:l){
    		num = num+s;
    	}
    	sum += Integer.valueOf(num);
    }
    return sum;
    }
    public ArrayList<ArrayList<String>> DFS(TreeNode root){
    	ArrayList<ArrayList<String>> res = new ArrayList<>();
    	if(root.left!=null){
    		ArrayList<ArrayList<String>> part = DFS(root.left);
    		for(ArrayList<String> p:part){
    			ArrayList<String> added = new ArrayList<>(p);
    			added.add(0,root.val+"");
    			res.add(added);
    		}
    	}
    	if(root.right!=null){
    		ArrayList<ArrayList<String>> part = DFS(root.right);
    		for(ArrayList<String> p:part){
    			ArrayList<String> added = new ArrayList<>(p);
    			added.add(0,root.val+"");
    			res.add(added);
    		}
    	}
    	if(root.left==null&&root.right==null){
    		ArrayList<String> add = new ArrayList<>();
    		add.add(root.val+"");
    		res.add(add);
    	}
    	return res;
    }

Log in to reply
 

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