ITeye博客

Path Sum II

KickCode · 2016-02-09 04:56 · Leetcode · 编程语言 · Markdown

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 ,

]

与Path Sum相比,这道题要求我们输出所有可能的结果,我们同样采用DFS,因为要输出所有可能的结果,我们用回溯法来记录,当找到符合条件的路径就记录下来,然后回溯,继续查找其它的路径。代码如下:


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        LinkedList<Integer> list = new LinkedList<Integer>();
        if(root == null) return result;
        getPath(root, 0, sum, result, list);
        return result;
    }
    public void getPath(TreeNode root, int count, int sum, List<List<Integer>> result, LinkedList<Integer> list) {
        if(root == null) return;
        count += root.val;
        list.add(root.val);
        if(count == sum && root.left == null && root.right == null) {
            result.add(new LinkedList<Integer>(list));
            list.removeLast();
            return;
        }
        getPath(root.left, count, sum, result, list);
        getPath(root.right, count, sum, result, list);
        list.removeLast();
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。