[LeetCode] 113. Path Sum II
来源:互联网 发布:linux 字符串编码转换 编辑:程序博客网 时间:2024/06/06 14:25
【原题】
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]]
【解释】
给定一颗二叉树和一个目标target,要求返回二叉树中从根节点到叶子结点的所有节点之和为target的路径。
【思路】
DFS的思想,若左右结点都遍历完之后,要将最后一个加入的结点删除,表示已经遍历过该节点所有的左右子女。
public class Solution { public void pathSumCore(List<List<Integer>> results, List<Integer> result,int sum,TreeNode root){ if(root==null) return; result.add(root.val); if(sum==root.val&&root.left==null&&root.right==null){ results.add(new ArrayList<>(result)); //result.remove(result.size()-1); //return ;//这里若要返回的话, 必须加前面的删除前面加入的路径 }else{ if(root.left!=null) pathSumCore(results,result,sum-root.val,root.left); if(root.right!=null) pathSumCore(results,result,sum-root.val,root.right); } result.remove(result.size()-1);//删除该结点 } public List<List<Integer>> pathSum(TreeNode root, int sum) { List<Integer> result=new ArrayList<Integer>(); List<List<Integer>> results=new ArrayList<List<Integer>>(); pathSumCore(results,result,sum,root); return results; }}
阅读全文
0 0
- 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
- 113. Path Sum II LeetCode
- 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
- 2017考研复试通关一定要解决的8个问题
- 如何写一个类
- bom编程
- 分布式爬虫学习
- 2017考研复试:过来人总结经验教训
- [LeetCode] 113. Path Sum II
- 20170628总结
- 常见函数封装工具(待补充)
- NOIP 2002提高组 均分纸牌
- Anhui Online Judge如何添加题目
- 在Ubuntu上安装Cinnamon Desktop
- maven命令行插件配置、pom中插件全局配置
- iOS addChildViewController 后拖拽失败
- Linux USB鼠标驱动程序详解