首页 > 其他 > 详细

Path Sum II

时间:2014-12-30 20:41:47      阅读:351      评论:0      收藏:0      [点我收藏+]

Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             /             4   8
           /   /           11  13  4
         /  \    /         7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]
要写出路径和满足要求的所有路径 典型的回溯法递归求解 代码如下:
public class Solution {
    public  List<List<Integer>> pathSum(TreeNode root, int sum) {
		List<List<Integer>> res=new ArrayList<List<Integer>>(0);
		List<Integer> tmp=new ArrayList<Integer>();
		pathsearch(res, tmp, sum, 0, root);
		return res;
	}
	public  void pathsearch(List<List<Integer>> res,List<Integer> tmp,int sum,int cur,TreeNode root){
		if(root==null)return;
		List<Integer> ntmp=new ArrayList<Integer>();
		ntmp.addAll(tmp);
		ntmp.add(root.val);
		if(root.left==null&&root.right==null){
			if(sum==cur+root.val){
				res.add(ntmp);
			}
			return;
		}
		
		if(root.left!=null){	
			pathsearch(res, ntmp, sum, cur+root.val, root.left);
		}
		if(root.right!=null){	
			pathsearch(res, ntmp, sum, cur+root.val, root.right);
		}
	}
}


Path Sum II

原文:http://blog.csdn.net/u012734829/article/details/42271195

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!