Leetcode-path-sum-ii
2016-08-02 15:27
148 查看
题目描述
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 andsum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
* public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.*; public class Solution { public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { ArrayList<ArrayList<Integer>> array = new ArrayList<ArrayList<Integer>>(); if(root == null) return array; ArrayList<Integer> list = new ArrayList<Integer>(); help(root, 0, sum, list, array); return array; } public void help(TreeNode root, int cur, int sum, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> array) { cur += root.val; list.add(root.val); if(root.left == null && root.right == null) { if(cur == sum) array.add(new ArrayList<Integer>(list)); } if(root.left != null) { help(root.left, cur, sum, list, array); } if(root.right != null) { help(root.right, cur, sum, list, array); } cur -= root.val; list.remove(list.size()-1); } }回溯、递归。不解释。因为解释太麻烦。
相关文章推荐
- leetcode:Path Sum II
- leetcode之Path Sum II
- Path Sum II - LeetCode 113
- LeetCode刷题(C++)——Path Sum II(Medium)
- [leetcode] @python 113. Path Sum II
- Leetcode-113 Path Sum II
- LeetCode--path-sum-ii
- Leetcode Path sum II
- 【LeetCode-面试算法经典-Java实现】【113-Path Sum II(路径和)】
- Java for LeetCode 113 Path Sum II
- LeetCode 113 Path Sum II (DFS)
- Path Sum II ---LeetCode
- LeetCode Path Sum II
- [leetcode]24 Path Sum II
- 【LeetCode】113.Path Sum II(Medium)解题报告
- leetcode 113 Path Sum II
- [LeetCode]Path Sum II
- LeetCode Path Sum II in Java
- LeetCode: Path Sum II
- Leetcode: Path Sum II