题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
Solution
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.Stack;
public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
int currentSum = 0;
Stack<TreeNode> stack = new Stack<TreeNode>();
ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
if(root == null)
return lists;
helper(root,target,currentSum,stack,lists);
return lists;
}
public void helper(TreeNode root,int target,int currentSum,Stack<TreeNode> stack,ArrayList<ArrayList<Integer>> lists){
currentSum += root.val;
stack.push(root);
boolean isLeaf = (root.left == null && root.right == null);
//如果是叶节点,而且路径上节点的和等于目标值,则打印路劲
if(currentSum == target && isLeaf){
ArrayList<Integer> list = new ArrayList<Integer>();
for(TreeNode s : stack){
list.add(s.val);
}
lists.add(list);
}
//如果不是叶节点,则遍历他的子节点
if(root.left != null){
helper(root.left,target,currentSum,stack,lists);
}
if(root.right != null){
helper(root.right,target,currentSum,stack,lists);
}
//返回父节点之前,在路径上删除当前节点
stack.pop();
}
}