文章目录

Problem:
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      1

return

[
   [5,4,11,2],
   [5,8,4,5]
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/

public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {

List<List<Integer>> pathList=new ArrayList<List<Integer>>();

if(root!=null)
pathSearch(pathList,new Stack<Integer>(),root,sum);

return pathList;
}

public void pathSearch(List<List<Integer>> pathList,Stack<Integer> curPath,TreeNode node,int sum)
{

if(node!=null)
{
curPath.push(node.val);
sum-=node.val;

if(node.left==null && node.right==null&&sum==0)
{
pathList.add(Collections.list(((Stack<Integer>)curPath.clone()).elements()));
}

pathSearch(pathList,curPath,node.left,sum);
pathSearch(pathList,curPath,node.right,sum);
curPath.pop();


}
}
}

本作品采用[知识共享署名-非商业性使用-相同方式共享 2.5]中国大陆许可协议进行许可,我的博客欢迎复制共享,但在同时,希望保留我的署名权kubiCode,并且,不得用于商业用途。如您有任何疑问或者授权方面的协商,请给我留言

文章目录