2014年2月13日星期四

LeetCode - Path Sum II

 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
return


[
   [5,4,11,2],
   [5,8,4,5]
]

/**
 * 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) {
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        if(root==null) {
            return ret;
        }
        ArrayList<Integer> ins = new ArrayList<Integer>();
        visit(root, sum, ins, 0, ret);
        return ret;
    }
    
    private void visit(TreeNode node, int sum, ArrayList<Integer> ins, int cur, ArrayList<ArrayList<Integer>> ret) {
        cur += node.val;
        ins.add(node.val);
        if(node.left==null && node.right==null && cur==sum) {
            ArrayList<Integer> good = new ArrayList<Integer>(ins);
            ret.add(good);
        } else {
            if(node.left!=null) {
                visit(node.left, sum, ins, cur, ret);
            }
            if(node.right!=null) {
                visit(node.right, sum, ins, cur, ret);
            }
        }
        sum -= node.val;
        ins.remove(ins.size()-1);
    }
}

没有评论:

发表评论