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
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [LeetCode]Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Leetcode: Path Sum II
- LeetCode-Path Sum II
- [leetcode] Path Sum II
- LeetCode - Path Sum II
- [LeetCode] Path Sum II
- Leetcode Path Sum II
- LeetCode | Path Sum II
- 【leetcode】Path Sum II
- [LeetCode] Path Sum II
- C#第二次作业
- 配置Java环境变量的原因
- 清华梦的粉碎—写给清华大学的退学申请(by王垠)
- 有趣的 linux命令行
- JUnit学习之hamcrest、testSuite介绍及测试原则
- LeetCode Path Sum II
- HTML5,不只是看上去很美(第二弹:打造最美3D机房)
- C#第三次作业
- ECMAScript5 DOM模型 Text详解
- 云端危机!原来,随身碟还是不能舍弃……
- 第十一篇 ANDROID 系统网络连接和管理机制
- C#四次作业
- 浅析,反编译 Android APK流程分享!
- Spring Data JDBC Extensions - Core JDBC Extensions (概述)