public boolean hasPathSum(TreeNode root, int sum) {
List<Integer> list = new ArrayList<>();
dfs(root, list);
List<String> strings = new ArrayList<>();
helper(root, root.val + "", strings);
System.out.println(strings.toString());
return true;
}
public void helper(TreeNode root, String path, List<String> result) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
result.add(path);
return;
}
if (root.left != null) {
helper(root.left, path + "->" + root.left.val, result);
}
if (root.right != null) {
helper(root.right, path + "->" + root.right.val, result);
}
}
输出list集合:
List<List<Integer>> results = new ArrayList<>();
public boolean hasPathSum(TreeNode root, int sum) {
List<Integer> list = new ArrayList<>();
dfs(root, list);
System.out.println(results.toString());
return true;
}
private void dfs(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
results.add(list);
}
list.add(root.val);
if (root.left != null) {
dfs(root.left, new ArrayList<>(list));
}
if (root.right != null) {
dfs(root.right, new ArrayList<>(list));
}
}