import java.util.ArrayList;
import java.util.Stack;
import java.util.Collections;
/**
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>> ret = new ArrayList<ArrayList<Integer>>();
if (root == null) {
return ret;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
int curSum = root.val;
ArrayList<Integer> tempRet = new ArrayList<>();
tempRet.add(root.val);
while (!stack.empty()) {
TreeNode currNode = stack.peek();
if (curSum < target) {
if (currNode.left != null) {
stack.push(currNode.left);
tempRet.add(currNode.left.val);
curSum += currNode.left.val;
currNode.left = null;
} else if (currNode.right != null) {
stack.push(currNode.right);
tempRet.add(currNode.right.val);
curSum += currNode.right.val;
currNode.right = null;
} else {
tempRet.remove(tempRet.size() - 1);
stack.pop();
curSum -= currNode.val;
}
} else if (curSum > target) {
stack.pop();
tempRet.remove(tempRet.size() - 1);
curSum -= currNode.val;
} else {
if (currNode.left == null && currNode.right == null) {
ret.add(tempRet);
ArrayList<Integer> tmp = new ArrayList<>();
for(int i = 0;i < tempRet.size();++i){
tmp.add(tempRet.get(i));
}
tempRet = tmp;
}
tempRet.remove(tempRet.size() - 1);
stack.pop();
curSum -= currNode.val;
}
}
return ret;
}
}
import java.util.Stack;
import java.util.Collections;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
深度优先遍历,然后在走不去之后,回退,为了避免重复,在把节点的左节点或右节点加入stack中后,
使其做节点或有节点指向空
*/public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
if (root == null) {
return ret;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
int curSum = root.val;
ArrayList<Integer> tempRet = new ArrayList<>();
tempRet.add(root.val);
while (!stack.empty()) {
TreeNode currNode = stack.peek();
if (curSum < target) {
if (currNode.left != null) {
stack.push(currNode.left);
tempRet.add(currNode.left.val);
curSum += currNode.left.val;
currNode.left = null;
} else if (currNode.right != null) {
stack.push(currNode.right);
tempRet.add(currNode.right.val);
curSum += currNode.right.val;
currNode.right = null;
} else {
tempRet.remove(tempRet.size() - 1);
stack.pop();
curSum -= currNode.val;
}
} else if (curSum > target) {
stack.pop();
tempRet.remove(tempRet.size() - 1);
curSum -= currNode.val;
} else {
if (currNode.left == null && currNode.right == null) {
ret.add(tempRet);
ArrayList<Integer> tmp = new ArrayList<>();
for(int i = 0;i < tempRet.size();++i){
tmp.add(tempRet.get(i));
}
tempRet = tmp;
}
tempRet.remove(tempRet.size() - 1);
stack.pop();
curSum -= currNode.val;
}
}
return ret;
}
}