题目:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路:用递归方法,前序遍历法,向辅助链表依次添加结点,并累加值,当访问至叶节点时,如果累加值与目标值相等,则将这个辅助链表保存至结果中,待返回。否则继续访问其子节点。*每次递归函数返回时,要回至其父节点,即辅助链表要删除最后一个数。
代码:
public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
if(root==null||target<=0){
return result;
}
ArrayList<Integer> helpAL=new ArrayList<Integer>();
int curSum=0;
FindPath(root,target,curSum,helpAL,result);
return result;
}
public void FindPath(TreeNode curNode,int target,int curSum,ArrayList<Integer> helpAL,ArrayList<ArrayList<Integer>> result){
curSum+=curNode.val;helpAL.add(curNode.val);
//若为叶节点,且和为路径,则完成
if(curNode.left==null&&curNode.right==null&&curSum==target){
result.add(new ArrayList<Integer>(helpAL));
helpAL.remove(helpAL.size()-1);
return;
}
if(curNode.left!=null){
FindPath(curNode.left,target,curSum,helpAL,result);
}
if(curNode.right!=null){
FindPath(curNode.right,target,curSum,helpAL,result);
}
helpAL.remove(helpAL.size()-1);
}
}