Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb9b46bc

Browse files
author
applewjg
committed
path sum2
Change-Id: I53f9100815f68d914630525e4dd897f3b9715757
1 parentbd9d3f6 commitb9b46bc

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

‎PathSum2.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Author: King, higuige@gmail.com
3+
Date: Oct 7, 2014
4+
Problem: Path Sum 2
5+
Difficulty: easy
6+
Source: https://oj.leetcode.com/problems/path-sum-ii/
7+
Notes:
8+
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
9+
10+
For example:
11+
Given the below binary tree and sum = 22,
12+
5
13+
/ \
14+
4 8
15+
/ / \
16+
11 13 4
17+
/ \ / \
18+
7 2 5 1
19+
return
20+
[
21+
[5,4,11,2],
22+
[5,8,4,5]
23+
]
24+
25+
Solution: DFS.
26+
*/
27+
28+
/**
29+
* Definition for binary tree
30+
* public class TreeNode {
31+
* int val;
32+
* TreeNode left;
33+
* TreeNode right;
34+
* TreeNode(int x) { val = x; }
35+
* }
36+
*/
37+
publicclassSolution {
38+
publicList<List<Integer>>pathSum(TreeNoderoot,intsum) {
39+
List<List<Integer>>res =newArrayList<List<Integer>>();
40+
ArrayList<Integer>path =newArrayList<Integer>();
41+
pathSumRe(root,sum,res,path);
42+
returnres;
43+
}
44+
publicvoidpathSumRe(TreeNoderoot,intsum,List<List<Integer>>res,ArrayList<Integer>path)
45+
{
46+
if (root ==null)return;
47+
path.add(root.val);
48+
if (root.left ==null &&root.right ==null &&root.val ==sum){
49+
ArrayList<Integer>tmp =newArrayList<Integer>(path);
50+
res.add(tmp);
51+
}
52+
pathSumRe(root.left,sum -root.val,res,path);
53+
pathSumRe(root.right,sum -root.val,res,path);
54+
path.remove(path.size()-1);
55+
}
56+
}
57+

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp