题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param target int整型
* @return int整型ArrayList<ArrayList<>>
*/
ArrayList<ArrayList<Integer>> path = new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> FindPath (TreeNode root, int target) {
// write code here
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> sub_path = new ArrayList<Integer>();
help(root, target, 0, sub_path, result);
return result;
}
void help(TreeNode root, int target, int sum, ArrayList<Integer> sub_path, ArrayList<ArrayList<Integer>> result) {
if (root == null) return;
sum += root.val;
sub_path.add(root.val);
if (sum == target && root.left == null && root.right == null) {
result.add(new ArrayList<Integer>(sub_path));
}
help(root.left, target, sum, new ArrayList<Integer>(sub_path), result);
help(root.right, target, sum, new ArrayList<Integer>(sub_path), result);
}
}
查看5道真题和解析
