题目描述:
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
思路:
采用先序遍历的方式依次遍历。访问到非叶子节点做好节点值累加和路径记录,访问到叶子结点判定一下至此累加的节点值是否为要判定的整数,若相等,需要备份当前路径并加到最终返回的链表中(注意arrayList为引用类型),访问过某个节点后要回退的话,别忘了从当前记录的路径中去掉这个节点。
参考代码:
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
ArrayList<ArrayList<Integer>> arrayList = new ArrayList<>();
if (root == null) {
return arrayList;
}
ArrayList<Integer> childList = new ArrayList<>();
checkPath(root, target, 0, arrayList, childList);
return arrayList;
}
public void checkPath(TreeNode node, int target, int sum, ArrayList<ArrayList<Integer>> aList,
ArrayList<Integer> childList) {
if (node.left == null && node.right == null) {
childList.add(node.val);
if (sum + node.val == target) {
ArrayList<Integer> childBackup = new ArrayList<>();
for (Integer integer : childList) {
childBackup.add(integer);
}
aList.add(childBackup);
}
} else {
childList.add(node.val);
if (node.left != null)
checkPath(node.left, target, sum + node.val, aList, childList);
if (!childList.isEmpty()) {
childList.remove(childList.size() - 1);
}
if(node.right != null)
checkPath(node.right, target, sum + node.val, aList, childList);
if (!childList.isEmpty()) {
childList.remove(childList.size() - 1);
}
}
}
}