题目描述
* FindPath功能:在给定root子树中,找出合理的路径以达到目标和target
* FindPath实质:二叉树的深度优先遍历 + 每次遍历均判断是否达到条件,若是则输出
* 大致策略
* 1、root入栈,跳入该子树进行寻路操作
* 2、若root的这条路径,已满足要求,则将该路径加入到listAll中去
* 3、对root左右子树,继续寻路
* 4、root出栈,该子树访问完毕
package jianzhioffer.tree;
import java.util.ArrayList;
/**
*
* @author hadoop
*
*/
public class FindPath {
private ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>();
private ArrayList<Integer> list = new ArrayList<Integer>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
if(root == null) return listAll;
list.add(root.val);
target -= root.val;
if(target == 0 && root.left == null && root.right == null)
listAll.add(new ArrayList<Integer>(list));
FindPath(root.left, target);
FindPath(root.right, target);
list.remove(list.size()-1);
return listAll;
}
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
}
以下为比较容易理解的答案:
import
java.util.ArrayList;
import
java.util.Stack;
public
class
Solution {
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> path,
ArrayList<ArrayList<Integer>> pathList) {
if
(root==
null
)
return
;
if
(root.left==
null
&&root.right==
null
){
if
(root.val==target){
ArrayList<Integer> list=
new
ArrayList<Integer>();
for
(
int
i:path){
list.add(
new
Integer(i));
}
list.add(
new
Integer(root.val));
pathList.add(list);
}
}
else
{
path.push(
new
Integer(root.val));
FindPath(root.left, target-root.val, path, pathList);
FindPath(root.right, target-root.val, path, pathList);
path.pop();
}
}
}