Path Sum II(LeetCode)
来源:互联网 发布:打印软件下载 编辑:程序博客网 时间:2024/06/06 09:50
题目:
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]]
题目分析:
这一题遇上一题类似,都是求根到叶子的路径和是否等于sum。不过,这一题要求将所有符合条件的路径返回。
思路:
- 深度优先遍历二叉树
- lastPath记录到父节点的路径,thisPath记录到本节点的路径
- 当是符合条件的叶子节点时,将thisPath放入result中。
- 否则,继续递归搜寻左孩子、右孩子
注意点:
- 对于引用类型,形参传递了指针的地址。当在方法中改变这一引用类型的时候,其值是被实际改变了。
- 所以getPath方法中,thisPath需要新建一个实例,才能再放入最后的result中或者传递给下一个递归地getPath
- 注意对于接口的使用
- 接口是不能使用所实现类的方法的。例如:List<Integer> thisPath = new ArrayList<Integer>(),thisPath只能用List接口中的方法addAll,而不能用ArrayList类中的方法clone。(不过,这一点不是十分的确定,需要再学习确认)
- 注意List接口中的addAll方法的使用,不用手工遍历复制了。(addAll是shallow copy)
代码:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { static List<List<Integer>> result; public List<List<Integer>> pathSum(TreeNode root, int sum) { result = new ArrayList<List<Integer>>(); List<Integer> thisPath = new ArrayList<Integer>(); getPath(root, sum, thisPath); return result; } static void getPath(TreeNode node, int sum, List<Integer> lastPath){ if (node == null){ return; } List<Integer> thisPath; if(node.left == null && node.right == null){ if(node.val == sum){ thisPath = new ArrayList<Integer>(); thisPath.addAll(lastPath); thisPath.add(node.val); result.add(thisPath); } return; } thisPath = new ArrayList<Integer>(); thisPath.addAll(lastPath); thisPath.add(node.val); getPath(node.left, sum - node.val, thisPath); getPath(node.right, sum - node.val, thisPath); }}
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
- 远程复制文件scp命令
- Oracle存储过程【带输入输出参数】
- LeetCode Set Matrix Zeroes
- java多线程基础学习-核心编程
- c#图片上写字
- Path Sum II(LeetCode)
- 中国国家气象局天气预报接口
- oracle 11g RAC crfclust.bdb过大的处理
- Android界面特效全汇总
- poj 3119 Friends or Enemies?(模拟)
- 系统杂类------让bat,cmd文件后台运行
- hdu2012- A计划
- 黑马程序员——java中的基本数据类型
- 简简单单的代码让你轻松学会 动态代理