Input a binary tree and an integer, print out all paths in the binary tree whose sum of node values is the input integer. A path is defined as a path from the root node of the tree down to the nodes passed by the leaf nodes.
Parse:
import java.util.ArrayList;
import java.util.Stack;
class TreeNode{
int val =0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
//递归实现路径的遍历,用栈记录访问过的节点。
public class findBinaryTreePath {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target){
ArrayList<ArrayList<Integer>> pathList = new ArrayList<ArrayList<Integer>>();
if(root == null)
return pathList;
Stack<Integer> stack = new Stack<Integer>();
FindPath(root,target,stack,pathList);
return pathList;
}
private void FindPath(TreeNode root, int target, Stack<Integer> stack, ArrayList<ArrayList<Integer>> pathList) {
// TODO Auto-generated method stub
if(root == null)
return;
if(root.left==null && root.right==null) {//基准条件 递归结束
if(root.val==target) {
ArrayList<Integer> list=new ArrayList<Integer>();
for(Integer i:stack) {
list.add(i);
}
list.add(root.val);
pathList.add(list);
}
}else { //递归演进,何时进行递归演进
stack.push(root.val);
FindPath(root.left,target-root.val,stack,pathList);
FindPath(root.right,target-root.val,stack,pathList);
stack.pop();
} //无需返回值
}
}