二、lintcode刷题记录--二叉树的路径和
2017-10-24 17:13
417 查看
LintCode刷题记录---二叉树的路径和(效率可能没有那些专业的高,主要是代码结构比较简单)
)
题目地址:http://www.lintcode.com/zh-cn/problem/binary-tree-path-sum/描述:
给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。一个有效的路径,指的是从根节点到叶节点的路径。
样例
给定一个二叉树,和
目标值 = 5:
1 / \ 2 4 / \ 2 3
返回:
[ [1, 2, 2], [1, 4] ]
代码实现:
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /* * @param root: the root of binary tree * @param target: An integer * @return: all valid paths */ public static List<Integer> tempList = new ArrayList<Integer>(); public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) { // write your code here List<List<Integer>> resLists = new ArrayList<List<Integer>>(); List<Integer> rlist = new ArrayList<Integer>(); seachTree(root, target, rlist, resLists); return resLists; } public static void seachTree(TreeNode node, int target ,List<Integer> rlist, List<List<Integer>> resLists){ if(node == null){ return; } List<Integer> tlist = new ArrayList<>(rlist); tlist.add(node.val); if(node.right == null && node.left == null){ if(jisuan(tlist) == target){ resLists.add(tlist); } } seachTree(node.right ,target , tlist, resLists ); seachTree(node.left ,target ,tlist, resLists ); } public static Integer jisuan(List<Integer> rlist){ Integer res = 0 ; for(Integer temp :rlist){ res = res + temp; } return res; } }
题后理解:
这道题也属于二叉树的遍历类型的题型,和之前的求二叉树最小值思路相同,在遍历的过程中将符合条件的值调价到结果集中。
代码思路:
1)、在主方法声明出结果集和对应结果集中的元素对象,然后使用递归方法遍历二叉树
2)、创建递归二叉树函数
如果为空直接返回,创建一个int集合将参数集合放入(原因下面有介绍)
解题注意事项:
代码中的遍历方法是将结果集中的int集合作为递归函数中的一个参数传入,自己刚开始直接将int集合放入结果集中
即:无下面代码
List<Integer> tlist = new ArrayList<>(rlist);
由于该参数int集合会随着递归方法变化而变化,导致结果将所有的节点元素都添加到结果集中,(有兴趣可以将上面的代码去掉,并将后面的对应的对象更改)
相关文章推荐
- LintCode-二叉树的所有路径
- lintcode--二叉树中的最大路径和
- lintcode binary-tree-paths 二叉树的所有路径
- 二叉树中路径和为某整数的所有路径 lint code by python
- lintcode----二叉树的所有路径
- LintCode 二叉树的所有路径
- Lintcode 376. 二叉树的路径和
- lintcode binary-tree-maximum-path-sum 二叉树中的最大路径和
- LintCode 二叉树的路径和
- LintCode 解题记录 17.5.8 (tag:二叉树)
- lintcode:二叉树的路径和
- LintCode2016年算法比赛----二叉树的所有路径
- LintCode-二叉树中的最大路径和
- lintcode:二叉树的所有路径
- lintcode(480)——二叉树的所有路径
- Lintcode——最小路径和
- LintCode 解题记录17.8.4 字符串处理2
- LintCode 114 不同的路径
- lintcode : 二叉树的最小深度
- LintCode2016年8月22日算法比赛----克隆二叉树