Leetcode-113 Path Sum II
来源:互联网 发布:苹果mac管理员密码忘记 编辑:程序博客网 时间:2024/05/01 02:07
问题描述
地址:https://leetcode.com/problems/path-sum-ii/#/description
描述:
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值,找出所有从根节点到叶子节点的路径,这些路径需要满足:路径上所有节点的和=sum
问题解析
设置两个list innerList 和 outerList
(1)从根节点向下遍历,一边遍历一边将节点值加和,并向innerList 中追加
(2)当遇到叶子节点的时候判断加和是否与sum相等
- 如果相等,则将innerList 添加到outerList中,同时去掉innerList中最后一个元素;
否则继续向innerList中追加
解析代码
public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> resultList = new ArrayList<List<Integer>>(); List<Integer> innerList = new ArrayList<Integer>(); pathSum(resultList, root, 0, innerList, sum); return resultList; } private void pathSum(List<List<Integer>> outerList, TreeNode root, int count, List<Integer> innerList, int sum) { if(root == null){ return ; } count += root.val; if(count == sum && root.left == null && root.right == null){ innerList.add(root.val); outerList.add(new ArrayList<Integer>(innerList)); innerList.remove(innerList.size()-1); return; } innerList.add(root.val); pathSum(outerList, root.left, count, innerList, sum); pathSum(outerList, root.right, count, innerList, sum); innerList.remove(innerList.size()-1); }
0 0
- LeetCode 113: Path Sum II
- LeetCode(113)Path Sum II
- LeetCode: Path Sum II [113]
- [leetcode 113] Path Sum II
- [LeetCode 113]Path Sum II
- leetcode || 113、Path Sum II
- Leetcode[113]-Path Sum II
- Path Sum II - LeetCode 113
- LeetCode(113) Path Sum II
- Leetcode #113 Path Sum II
- leetcode 113: Path Sum II
- LeetCode 113: Path Sum II
- LeetCode 113 Path Sum II
- LeetCode 113:Path Sum II
- LeetCode 113 Path Sum II
- leetcode 113 Path Sum II
- Leetcode 113 Path Sum II
- leetcode 113 Path Sum II
- 微信支付模式一和模式二的区别
- DWR
- Servlet_1th_第一个Servlet程序
- Oracle数据笔记-【6】触发器和内置程序包
- 欢迎使用CSDN-markdown编辑器
- Leetcode-113 Path Sum II
- Win10+Ubuntu16.04双系统安装教程之1
- 黄金连分数
- 使用OpenSessionInViewFilter后 could not initialize proxy no session
- 【LeetCode】常用算法之Quick Select
- 【EM算法】在高斯混合模型中的应用及python示例
- python3学习笔记:函数作为返回值&匿名函数lambda
- skywang12345的博客
- Android-ndk 调用现有的动态库