题解 | #二叉树根节点到叶子节点和为指定值的路径#
二叉树根节点到叶子节点和为指定值的路径
http://www.nowcoder.com/practice/840dd2dc4fbd4b2199cd48f2dadf930a
dfs+回溯
import java.util.*;
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
}
public class Solution {
/**
*
* @param root TreeNode类
* @param sum int整型
* @return int整型ArrayList<ArrayList<>>
*/
private ArrayList<ArrayList<Integer>> result;
private int target;
void dfs(TreeNode root, ArrayList<Integer> path, int sum) {
if (root == null) return;
if (isLeaf(root)) {
if (sum + root.val == target) {
ArrayList<Integer> newPath = (ArrayList<Integer>) path.clone();
newPath.add(root.val);
result.add(newPath);
}
return;
}
path.add(root.val);
if (root.left != null) {
dfs(root.left, path, sum + root.val);
}
if (root.right != null) {
dfs(root.right, path, sum + root.val);
}
path.remove(path.size()-1);
}
boolean isLeaf(TreeNode root) {
if (root.right == null && root.left == null) {
return true;
}
return false;
}
public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
result = new ArrayList<>();
target = sum;
dfs(root, new ArrayList<>(), 0);
return result;
}
}