113-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.
Note: A leaf is a node with no children.
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
問題分析
解法
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList();
if(root == null) return res;
findPath(root, res, new ArrayList(), sum);
return res;
}
public void findPath(TreeNode root, List<List<Integer>> res, List<Integer> line, int sum){
line.add(root.val);
sum -= root.val;
if(root.left == null && root.right == null && sum == 0) res.add(new ArrayList(line));
if(root.left != null) findPath(root.left, res, line, sum);
if(root.right != null) findPath(root.right, res, line, sum);
line.remove(line.size() - 1);
}
}
相關文章
- Leetcode 40 Combination Sum IILeetCode
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- 秒殺 2Sum 3Sum 4Sum 演算法題演算法
- GCD SUMGC
- Sum Problem
- 集合sum
- 15+18、3Sum 4Sum
- Range Minimum Sum
- B - Minimum Sum
- Missing Subsequence Sum
- Path Sum III
- Leetcode Path SumLeetCode
- leetcode Sum系列LeetCode
- Sum of Left Leaves
- Path-sum
- Range Addition II 範圍求和 II
- LeetCode | 1 Two SumLeetCode
- SQL groupby sum 用法SQL
- 7.22 APPROX_SUMAPP
- the Sum of Cube hd 5053
- Leetcode 39 Combination SumLeetCode
- md5sum
- 112-Path Sum
- Leetcode 1 two sumLeetCode
- Hackable: II
- (原創) 如何破解Quartus II 7.2 SP1? (IC Design) (Quartus II) (Nios II)iOS
- B. Missing Subsequence Sum
- LeetCode-1 Two SumLeetCode
- LeetCode 112. Path SumLeetCode
- tf.reduce_sum用法
- python: leetcode - 1 Two SumPythonLeetCode
- python--iter()+next()+sum()Python
- 829. Consecutive Numbers Sum
- leetcode-39-Combination SumLeetCode
- [LintCode] 3Sum Smaller
- Linux基礎命令—sumLinux
- Leetcode 15 3SumLeetCode
- Leetcode 18 4SumLeetCode