剑指offer-25 二叉树中和为某一值的路径
来源:互联网 发布:cf积分刷点卷软件 编辑:程序博客网 时间:2024/06/06 18:39
思考
- 判断路径肯定使用深度遍历;
- 遍历到一个叶结点后需要返回上一父节点;因此在函数的最后应该将末尾元素删除;
- 保存结果方式,不可能在函数中定义容器,因此可以将结果作为函数参数,在函数递归过程中依次更新数据。(类似mergeSort中将整理的数组传递给新建的空间数组,最后再遍历更新原来的数组)
代码
public static ArrayList<ArrayList<Integer>> FindPath(BinaryTree root, int target) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> tmp = new ArrayList<Integer>(); if(root == null) return res; DFS(root, target, 0, res, tmp); return res; } public static void DFS(BinaryTree root, int target, int curSum, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp){ if(root != null){ curSum += root.val; tmp.add(root.val); boolean isLeaf = (root.left == null) && (root.right == null); if(curSum == target){ if(isLeaf){ ArrayList<Integer> t2 = new ArrayList<Integer>(); //之前是保存的tmp,很明显在每次迭代过程中tmp都会变化, for(int i = 0; i < tmp.size(); i++){ //最后为空,所以应该新建 t2.add(tmp.get(i)); } res.add(t2); } }else if(curSum < target){ DFS(root.left, target, curSum, res, tmp); DFS(root.right, target, curSum, res, tmp); } tmp.remove(tmp.size()-1); // 记得每次遍历后将该节点的值删除。 } }
总结
- 保存每条路径的tmp在整个函数过程中不断更新,因此不可能将其保存到最终结果中,需要每次找到合适的路径后新建一个ArrayList复制数据;
- 注意,每次递归遍历当前节点结束后,会自动回到它的父节点,因此保存路径的tmp删除当前节点的值。
0 0
- 剑指offer:二叉树中和为某一值的路径
- 【剑指offer】二叉树中和为某一值的路径
- 剑指offer--二叉树中和为某一值的路径
- 《剑指offer》二叉树中和为某一值的路径
- 【剑指Offer】二叉树中和为某一值的路径
- 剑指Offer--二叉树中和为某一值的路径
- 剑指offer:二叉树中和为某一值的路径
- 剑指offer 二叉树中和为某一值的路径
- 剑指offer:二叉树中和为某一值的路径
- [剑指offer]二叉树中和为某一值的路径
- 《剑指offer》-二叉树中和为某一值的路径
- 剑指offer 二叉树中和为某一值的路径
- 【剑指offer】二叉树中和为某一值的路径
- 剑指offer|二叉树中和为某一值的路径
- 《剑指offer》二叉树中和为某一值的路径
- 剑指offer 二叉树中和为某一值的路径
- 剑指Offer:二叉树中和为某一值的路径
- 剑指offer-二叉树中和为某一值的路径
- 解密史上最赚钱的理财规划
- 06:登山
- Unity5.x AssetsBundle笔记
- 【工具】Glide基本使用方法说明与圆角图片工具
- shell脚本不可以执行原因
- 剑指offer-25 二叉树中和为某一值的路径
- 如何查看某个端口被谁占用
- Path Sum III
- 初学者的MySQL 1067 错误解决方法
- 【Dubbo】dubbo连接zookeeper注册中心因为断网导致线程无限等待问题
- C#学习日记 字典
- Java SE、Java EE、Java ME三者的区别
- 概率计算 蓝桥杯 C语言
- HTML5+CSS3整体回顾