Path Sum II, Leetcode 解题笔记

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]
]

与上一题基本一样,遇到符合条件的情况加到list里即可。

/**
 * 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>>();
        ArrayList<Integer> sol = new ArrayList<Integer>();
        if(root == null) return ret;
        sol.add(root.val);
        dfs(ret, sol, root, sum-root.val);
        return ret;
    }
    public void dfs(ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> sol, TreeNode root, int sum){
        if(root == null) return;
        if(root.left == null && root.right == null && sum == 0){
            ret.add(new ArrayList(sol));
        }
        else{
            if(root.left != null){
            sol.add(root.left.val);
            dfs(ret, sol, root.left, sum - root.left.val);
            sol.remove(sol.size()-1);
            }
            
            if(root.right != null){
            sol.add(root.right.val);
            dfs(ret, sol, root.right, sum - root.right.val);
            sol.remove(sol.size()-1);
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s