Path Sum II 解答
2015-09-30 23:24
197 查看
Question
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
Traditional way, use DFS and recursion./** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> result = new ArrayList<List<Integer>>(); List<Integer> prevList = new ArrayList<Integer>(); dfs(root, sum, result, prevList); return result; } private void dfs(TreeNode root, int target, List<List<Integer>> result, List<Integer> prevList) { if (root == null) return; prevList.add(root.val); if (root.left == null && root.right == null) { if (root.val == target) result.add(new ArrayList<Integer>(prevList)); } else { List<Integer> tmpList2 = new ArrayList<Integer>(prevList); if (root.left != null) dfs(root.left, target - root.val, result, prevList); if (root.right != null) dfs(root.right, target - root.val, result, tmpList2); } } }
相关文章推荐
- 开发环境配置及优化
- 一个简单地C语言程序展示RSA加密原理
- ArtTemplate模板引擎入门
- [置顶] 细谈Struts2框架(一) Struts2框架之原理
- C++——Static变量初始化
- jquery一些技巧总结
- The State of Front-End Tooling – 2015
- 细谈Struts2框架(四)Struts2框架之标签库
- 谈谈jquery性能优化的常用策略
- 多线程中的同步
- RAW碰到的问题与功能的测试
- ORACLE 11g用户权限管理随笔精髓
- 2015年英语学习——9月
- [经济生活基本知识]社会主义市场经济
- ZOJ 2932
- c# panel里面嵌入窗体
- JavaWeb 创建省市级关联菜单
- 《编程之美》--字符串移位包含的问题
- 前端自动化:谈谈grunt和gulp的区别
- 细谈Struts2框架(三)Struts2框架之ModelDriven