題目:
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] ]
思考:
代碼(java):
/**
* Definition for a binary tree node.
* 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>> totalPath = new ArrayList<List<Integer>>();
int total = 0;
List<Integer> currentPath = new ArrayList<Integer>();
find(root, sum, currentPath, total, totalPath);
return totalPath;
}
public void find(TreeNode root, int sum, List<Integer> currentPath, int total, List<List<Integer>> totalPath){
if(root == null){
return;
}
currentPath.add(root.val);
total = total + root.val;
if(root.left == null && root.right == null && total == sum){
totalPath.add(new ArrayList(currentPath));
return;
}
//首先會一直遍歷left,然後纔是慢慢的往上走,取查看他的兄弟,所以需要刪除最後一個!
if(root.left != null){
//currentPath.add(root.val);
//total = total + root.val;
find(root.left, sum, currentPath, total, totalPath);
currentPath.remove(currentPath.size() - 1);
}
if(root.right != null){
//currentPath.add(root.val);
//total = total + root.val;
find(root.right, sum, currentPath, total, totalPath);
currentPath.remove(currentPath.size() - 1);
}
}
}