标签:
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
import java.util.ArrayList;
import java.util.Stack;
/**
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>> list = new ArrayList<ArrayList<Integer>>();
if (root == null || target == 0) {
return list;
}
Stack<Integer> stack = new Stack<Integer>();
int sum = 0;
find(root, list, stack, sum, target);
return list;
}
public void find(TreeNode root, ArrayList list, Stack<Integer> stack, int sum, int target) {
sum += root.val;
stack.push(root.val);
boolean isLeaf = (root.left == null) && (root.right == null);
// 如果是叶结点,并且总和等于target
// 存储该路径
if ((sum == target) && isLeaf) {
ArrayList<Integer> intList = new ArrayList<Integer>();
for (Integer x: stack) {
intList.add(x);
}
list.add(intList);
}
// 如果不是叶子结点,遍历左右子结点
if (root.left != null) {
find(root.left, list, stack, sum, target);
}
if (root.right != null) {
find(root.right, list, stack, sum, target);
}
// 返回父节点之前,在路径上删除当前结点
// 并在sum中减去该值
sum -= root.val;
stack.pop();
}
}
标签:
原文地址:http://www.cnblogs.com/rosending/p/5628064.html