码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 113 Path Sum II

时间:2015-05-23 21:16:11      阅读:196      评论: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]
]
 

解题思路:

DFS,JAVA实现如下:

	static public List<List<Integer>> pathSum(TreeNode root, int sum) {
		List<List<Integer>> list = new ArrayList<List<Integer>>();
		List<Integer> alist = new ArrayList<Integer>();
		if (root != null)
			dfs(alist,list, root, sum);
		return list;
	}

	public static void dfs(List<Integer> alist,List<List<Integer>> list, TreeNode root, int sum) {
		if (root.left == null && root.right == null) {
			if (sum == root.val) {
				alist.add(root.val);
				list.add(new ArrayList<Integer>(alist));
				alist.remove(alist.size() - 1);
			}
			return;
		}
		alist.add(root.val);
		if (root.left == null)
			dfs(alist,list, root.right, sum - root.val);
		else if (root.right == null)
			dfs(alist,list, root.left, sum - root.val);
		else {
			List<Integer> alistCopy = new ArrayList<Integer>(alist);
			dfs(alist,list, root.right, sum - root.val);
			alist=alistCopy;
			dfs(alist,list, root.left, sum - root.val);
		}

	}

 

Java for LeetCode 113 Path Sum II

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4524858.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!