LeetCode Path Sum II

来源:互联网 发布:淘宝助手官网下载 编辑:程序博客网 时间:2024/05/16 18:43

Description:

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

Solution:

还是一样的DFS。

和Path Sum相比,有一个细节:DFS的每个层次递归的条件有所不同。

import java.util.*;public class Solution {int targetSum;List<List<Integer>> list = new ArrayList<List<Integer>>();public List<List<Integer>> pathSum(TreeNode root, int sum) {if (root == null)return list;this.targetSum = sum;ArrayList<Integer> array = new ArrayList<Integer>();array.add(root.val);dfs(root, root.val, array);return list;}void dfs(TreeNode root, int tempSum, ArrayList<Integer> array) {if (root.left == null && root.right == null) {if (tempSum == targetSum)list.add(new ArrayList<Integer>(array));}if (root.left != null) {array.add(root.left.val);dfs(root.left, tempSum + root.left.val, array);array.remove(array.size() - 1);}if (root.right != null) {array.add(root.right.val);dfs(root.right, tempSum + root.right.val, array);array.remove(array.size() - 1);}}}


0 0