剑指offer-二叉树中某一路径的和为给定值

输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

/**
 * 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
 * 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
 * 其实我一开始并没有想到先序遍历,而是用类似深搜的方法,不断地往下走,直到找到叶节点
 * 然后看sum是否与target相等
 * 但有个问题就是,遍历完某个结点的左孩子后,在遍历右孩子的时候,发现左孩子留了在list中。
 * 有一个办法就是在遍历之前再建立一个一模一样的list,这就是额外的空间消耗了。
 * 用先序遍历其实思路一样,但是用的是一个栈来维护,在遍历完某个结点的左右孩子后,需要将这个节点出栈。
 * @author admin
 *
 */
public class PathSum {
	public static ArrayList<ArrayList<Integer>> results=new ArrayList<ArrayList<Integer>>();
	 public static ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
	        if(root==null||target<root.val){
	        	return results;
	        }
	        findPath(root,0,target,new ArrayList<Integer>());
	        return results;
	        
	  }
	 public static void findPath(TreeNode current,int sum,int target,ArrayList<Integer> stack){
		 if(current!=null) {
			 stack.add(current.val);
			 sum+=current.val;
			 if(current.left==null&&current.right==null) {
				 if(sum==target){//如果sum==target则加进结果集中
					 results.add(new ArrayList<Integer>(stack));
				 }
				 //如果不相等,也需要出栈,所以这里不return
			 }
			 if(current.left!=null){
				 findPath(current.left,sum,target,stack);
			 }
			 if(current.right!=null){
				 findPath(current.right,sum,target,stack);
			 }
			 //current结点出栈
			 stack.remove(stack.size()-1);
		 }
	 }
}

  

原文地址:https://www.cnblogs.com/qingfei1994/p/4900200.html