LeetCode 113 Path Sum II

来源:互联网 发布:海知智能上市了吗 编辑:程序博客网 时间:2024/05/22 06:19

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

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution2 {List<List<Integer>> result = new ArrayList<List<Integer>>();List<Integer> path = new ArrayList<Integer>();public List<List<Integer>> pathSum(TreeNode root, int sum) {dfs(root, sum);return result;}private void dfs(TreeNode root, int sum) {if (root == null) return;path.add(root.val);sum -= root.val;if (sum == 0 && root.left == null && root.right == null)/**一定要注意这里要new一个新的list,因为path在变化.**/result.add(new ArrayList<Integer>(path));path.addAll(path);dfs(root.left, sum);dfs(root.right, sum);/**因为计算新的path的时候,path要清空,所以回归的时候,把本次放进的元素移除**/path.remove(path.size() - 1);}}


0 0
原创粉丝点击