Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created August 21, 2013 05:31
Show Gist options
  • Select an option

  • Save charlespunk/6290650 to your computer and use it in GitHub Desktop.

Select an option

Save charlespunk/6290650 to your computer and use it in GitHub Desktop.
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]
]
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> all = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> one = new ArrayList<Integer>();
hasPathSum(sum, root, one, all);
return all;
}
private void hasPathSum(int last, TreeNode root, ArrayList<Integer> one,
ArrayList<ArrayList<Integer>> all){
if(root == null) return;
one.add(root.val);
int now = last - root.val;
if(root.left == null && root.right == null){
if(now == 0) all.add(new ArrayList<Integer>(one));
}
else{
hasPathSum(now, root.left, one, all);
hasPathSum(now, root.right, one, all);
}
one.remove(one.size() - 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment