[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); 
        }
    }
}

  

posted @ 2013-08-08 22:58  阿牧遥  阅读(168)  评论(0编辑  收藏  举报