[leetcode]Path Sum II

简单题。现在对于这种递归已经很熟练了啊。

/**

 * Definition for binary tree

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode(int x) { val = x; }

 * }

 */

public class Solution {

    public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {

        // Start typing your Java solution below

        // DO NOT write main() function

        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();

        ArrayList<Integer> arr = new ArrayList<Integer>();

        PathSum(root, sum, arr, ret);

        

        return ret;

    }

    

    public void PathSum(TreeNode root, int sum, ArrayList<Integer> arr, ArrayList<ArrayList<Integer>> ans) {

        if (root == null) return;

        if (root.left == null && root.right == null && root.val == sum) {

            arr.add(root.val);

            ArrayList<Integer> tmp = new ArrayList<Integer>();

            for (int i = 0; i < arr.size(); i++) {

                tmp.add(arr.get(i));

            }

            ans.add(tmp);

            arr.remove(arr.size() - 1);            

        }

        else {

            arr.add(root.val);

            PathSum(root.left, sum - root.val, arr, ans);

            arr.remove(arr.size() - 1); 

            

            arr.add(root.val);

            PathSum(root.right, sum - root.val, arr, ans);

            arr.remove(arr.size() - 1); 

        }

    }

}

  

你可能感兴趣的:(LeetCode)