Problem(root to any)

Your are given a binary tree in which each node contains a value. Design an algorithm to get all paths which sum to a given value. The path does not need to start or end at the root or a leaf, but it must go in a straight line down.

Example
Given a binary tree:

    1
   / \
  2   3
 /   /
4   2
for target = 6, return

[
  [2, 4],
  [1, 3, 2]
]

思路(traverse)

  1. 参数不多解释
  2. path总是从root开始到达某一个点, 然后我们计算是否满足target
  3. 我们复制这个path, 并且将起点更改成它后面的点, 看看所组成的target是否满足, 是的话加入result中
    public List<List<Integer>> binaryTreePathSum2(TreeNode root, int target) {
        List<List<Integer>> result = new ArrayList<>();
        helper(root, target, result, new ArrayList<Integer>());
        return result;
    }

    private void helper(TreeNode root, int target, List<List<Integer>> result, List<Integer> path) {
        if (root == null) return;

        path.add(root.val);
        target -= root.val;

        if (target == 0) {
            result.add(new ArrayList<Integer>(path));
        }

        int temp = target;
        List<Integer> list = new LinkedList<>(path);
        while (list.size() > 1) {
            temp += list.get(0);
            list.remove(0);
            if (temp == 0) {
                result.add(new ArrayList<Integer>(list));
            }
        }

        helper(root.left, target, result, path);
        helper(root.right, target, result, path);

        path.remove(path.size() - 1);
        target += root.val;
    }

results matching ""

    No results matching ""