LeetCode - Path Sum II
2016-01-10 13:29
393 查看
题目:
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
思路:
注意必须到 leaf node
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] ]
思路:
注意必须到 leaf node
package tree; import java.util.ArrayList; import java.util.List; public class PathSumII { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if (root == null) return res; List<Integer> record = new ArrayList<Integer>(); pathSum(res, record, root, sum); return res; } private void pathSum(List<List<Integer>> res, List<Integer> record, TreeNode root, int sum) { if (root == null && sum != 0) return; if (root == null && sum == 0) { res.add(record); } else { if (root.left == null || root.right == null) { List<Integer> newRecord = new ArrayList<Integer>(record); newRecord.add(root.val); pathSum(res, newRecord, root.left == null ? root.right : root.left, sum - root.val); } else { List<Integer> newRecord1 = new ArrayList<Integer>(record); newRecord1.add(root.val); pathSum(res, newRecord1, root.left, sum - root.val); List<Integer> newRecord2 = new ArrayList<Integer>(record); newRecord2.add(root.val); pathSum(res, newRecord2, root.right, sum - root.val); } } } }
相关文章推荐
- 从零开始写javaweb框架笔记10-搭建轻量级JAVAWEB框架-确定目标
- powerbuilder调用dsoframer.ocx组件及操作 pb内嵌word组件及操作
- 燕十八---CSS画三角形
- Apache2 虚拟主机 详解
- css3实现图片旋转效果
- 选择排序
- Http请求
- 编程语言的故事(一)
- iostat
- HTML5调用摄像头实现拍照功能(兼容各大主流浏览器)
- Google的Java编程风格指南(Java编码规范)
- linux系统下源码安装Apache2.4
- 统计互不相同且无重复数字的三位数个数
- new delete与malloc free之内存管理(1)
- 从Hadoop到Spark的架构实践
- 【Linux】教你一步一步在CentOS Linux release 7.1上安装vsftpd FTP服务器
- C/C++基本数据类型所占字节数
- Golang初级系列教程-控制结构-defer语句
- jquery实现二级菜单
- DOM知识点