《leetCode》:Path Sum II
来源:互联网 发布:欢聚时代程序员的工资 编辑:程序博客网 时间:2024/06/05 23:02
题目
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 1return[ [5,4,11,2], [5,8,4,5]]
思路
首先判断当前结点root是否是叶子节点,如果不是,则将此节点值保存,然后分别在此节点的左右子树中寻找是否存在路径之和满足(sum-root.val);如果是叶子节点,则判断该节点的值是否等于sum,如果等于,则符合要求。
实现代码如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { private List<List<Integer>> res=new ArrayList<List<Integer>>(); public List<List<Integer>> pathSum(TreeNode root, int sum) { pathSumHelper(new ArrayList<Integer>(),root,sum); return res; } private void pathSumHelper(ArrayList<Integer> arrayList, TreeNode root, int sum) { if(root==null){ return ; } arrayList.add(root.val); if(root.left==null&&root.right==null){ if(sum==root.val){//符合条件的则将其加入 res.add(arrayList); } } //如果此节点不是叶子节点,则 pathSumHelper(new ArrayList<Integer>(arrayList),root.left,sum-root.val); pathSumHelper(new ArrayList<Integer>(arrayList),root.right,sum-root.val); }}
1 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
- HBase shell使用教程
- Apple Pay接入详细教程
- 【机器学习算法】之KNN算法的实现
- 【Some】【搞逗】如何向外行解释产品经理频繁更改需求为什么会令程序员烦恼?
- could not get lock/var/lib/dpkg/lock(ubuntu常见错误)
- 《leetCode》:Path Sum II
- 关于一个关系型数据库的实现原理参考
- android 获取路径目录方法
- java 泛型初探
- MapReduce中的分布式缓存使用
- js修改时间
- 途牛原创|XMPP协议在途牛APP中的应用实践
- 自旋锁与互斥锁
- 通过设置AUTO_INCREMENT设置自增起始值