Path Sum II
来源:互联网 发布:微表情软件白金版 编辑:程序博客网 时间:2024/05/20 12:48
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]]
要写出路径和满足要求的所有路径 典型的回溯法递归求解 代码如下:
public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) {List<List<Integer>> res=new ArrayList<List<Integer>>(0);List<Integer> tmp=new ArrayList<Integer>();pathsearch(res, tmp, sum, 0, root);return res;}public void pathsearch(List<List<Integer>> res,List<Integer> tmp,int sum,int cur,TreeNode root){if(root==null)return;List<Integer> ntmp=new ArrayList<Integer>();ntmp.addAll(tmp);ntmp.add(root.val);if(root.left==null&&root.right==null){if(sum==cur+root.val){res.add(ntmp);}return;}if(root.left!=null){pathsearch(res, ntmp, sum, cur+root.val, root.left);}if(root.right!=null){pathsearch(res, ntmp, sum, cur+root.val, root.right);}}}
0 0
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [113]Path Sum II
- Path Sum II
- Path Sum II
- [LeetCode]Path Sum II
- Path Sum II
- Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Path Sum II
- Leetcode: Path Sum II
- Path Sum II
- git笔记
- arm-linux工具的功能
- 禁止键入非法值
- [Leetcode]Remove Duplicates from Sorted List II
- ORCAD 快速加页码
- Path Sum II
- Root of AVL Tree
- oracle connect by level 的用法
- WPF-绑定
- 关于链表的总结(一套链表定义)
- SQLiteOpenHelper简介
- bzoj1486: [HNOI2009]最小圈 二分+dfs判环
- 解决CentOS系统的分辨率不合适的问题
- python监控脚本的编写