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

链接: http://leetcode.com/problems/path-sum-ii/

题解:

与上一题不同的是,要存储所有的root - leaf路径,所以在DFS的基础上我们还要增加backtracking。回溯的点有两个,一个是当前root满足条件,返回时,此时回溯保证当前root的sibling结果正确; 另外一个是遍历完当前root的左子树和右子树时, 这时回溯也是保证sibling结果正确。比如 root = [0, 1, 1], sum = 1,则计算完左边的1时可以正确计算到右边的1。或者 root = [0, 1, 1, 0, 0], sum = 1, 遍历完左边的两个0后可以正确计算到右边1的结果。 (有空要组织一下语言)

Time Complexity - O(n), Space Complexity - O(n)。

/**
 * 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>> res = new ArrayList<>();
        ArrayList<Integer> list = new ArrayList<>();
        dfs(res, list, root, sum);
        return res;
    }
    
    private void dfs(List<List<Integer>> res, ArrayList<Integer> list, TreeNode root, int sum) {
        if(root == null)
            return;
        if(root.left == null && root.right == null && root.val == sum) {
            list.add(root.val);
            res.add(new ArrayList<Integer>(list));
            list.remove(list.size() - 1);
            return;
        }
        
        list.add(root.val);
        sum -= root.val;
        dfs(res, list, root.left, sum);
        dfs(res, list, root.right, sum);
        list.remove(list.size() - 1);
    }
}

 

二刷:

注意回溯的点。

Java:

/**
 * 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>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        pathSum(res, list, root, sum);
        return res;
    }
    
    private void pathSum(List<List<Integer>> res, List<Integer> list, TreeNode root, int sum) {
        if (root == null) return;
        sum -= root.val;
        list.add(root.val);
        if (root.left == null && root.right == null && sum == 0) {
            res.add(new ArrayList<>(list));
            list.remove(list.size() - 1);
            return;
        }
        pathSum(res, list, root.left, sum);
        pathSum(res, list, root.right, sum);
        list.remove(list.size() - 1);
    }
}

 

测试:

posted @ 2015-04-18 13:59  YRB  阅读(609)  评论(0编辑  收藏  举报