leetcode:Path Sum II 【Java】
2016-03-08 10:15
405 查看
一、问题描述
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
二、问题分析
详见代码。
三、算法代码
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 Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> result = new ArrayList<List<Integer>>(); List<Integer> segRes;//保存中间结果 //每次迭代都独立创建一个list保存本次搜索结果 pathSum(root, sum, new ArrayList<Integer>(), result); return result; } public void pathSum(TreeNode root, int gap, List<Integer> segRes, List<List<Integer>> result){ if(root == null){ return;//本轮递归结束 } segRes.add(root.val); if(root.left == null && root.right == null){ //叶子结点 if(gap == root.val){//该叶子结点值等于最后的差值 result.add(segRes); return; //本轮递归结束 } } //注意是带参数的new ArrayList<Integer>(segRes),需要携带前面的中间结果 pathSum(root.left, gap - root.val, new ArrayList<Integer>(segRes), result); pathSum(root.right, gap - root.val, new ArrayList<Integer>(segRes), result); } }
相关文章推荐
- Pat1012. 数字分类 (20)
- Hashtable与hashmap 比较
- Java中,BigDecimal互转Integer
- java文件路径的不同写法
- java web每天定时执行任务
- Java锁的种类以及辨析
- struts国际化配置
- 包含min函数的栈Java
- 使用Eclipse构建Maven项目 (step-by-step)
- 【leetcode】【153】Find Minimum in Rotated Sorted Array
- propertiesfactorybean vs propertyplaceholderconfigurer spring?
- Spring 使用注解方式进行事务管理
- JAVA代码实现MD5加密算法
- Eclipse下配置Ant脚本并自动打包带签名的Android apk
- 【leetcode】【145】Binary Tree Postorder Traversal
- ClassNotFoundException和NoClassDefFoundError的区别
- Java中getResourceAsStream的用法
- struts2 大白话原理简介
- java中的各种数据类型在内存中存储的方式
- 使用IntelliJ IDEA 15和Maven创建Java Web项目