Java recursive solution


  • 0
    C
    public void getPath(TreeNode root, int sum, String path){
        if(root == null) return;
        if(root.val == sum && root.left == null && root.right == null){
            path+=root.val;
            list.add(new ArrayList<Integer>());
            String[] arr = path.split("->");
            for(String s: arr){
                if(!s.equals("") && !s.equals(" ")){
                    list.get(count).add(Integer.parseInt(s));
                }
            }   
            count++;
        }
        getPath(root.left, sum-root.val, path+root.val+"->");
        getPath(root.right, sum-root.val, path+root.val+"->"); 
    }

Log in to reply
 

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