LeetCode Path Sum II
2015-07-07 12:10
288 查看
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
return
Solution:
还是一样的DFS。
和Path Sum相比,有一个细节:DFS的每个层次递归的条件有所不同。
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); } } }
相关文章推荐
- 解读高通反垄断调查中的四个真相
- 清华梦的粉碎—写给清华大学的退学申请(by王垠)
- 配置Java环境变量的原因
- C#第二次作业
- JUnit学习之JUnit的基本介绍
- Microsoft Dynamics CRM 2013 Reporting Extensions 正式安装
- Invert Binary Tree
- 对目录中的所有文件执行一系列指令且自动获取参数的脚本
- android studio 更改包名让android识别为新的app
- Java 接口和抽象类区别
- 用“倍增法”求最近公共祖先(LCA)
- 数据挖掘研究方向、热点以及对大数据研究的认识
- Android 增强版百分比布局库 为了适配而扩展
- eclipse debug java源码时时总是显示 source not found
- android 自动获取短信验证码
- 小小木雨
- PLSQL Developer建表时注释(COMMENT)中文乱码的解决方案(Windows)
- Python中的urllib模块使用详解
- Xcode5 证书配置
- Linux常用命令