码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Path Sum II

时间:2015-05-10 09:43:32      阅读:103      评论: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]
]
题意:求路径和为sum的所有可能。

思路:和上一题差不多,多个记录而已。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private List<List<Integer>> ans = new ArrayList<List<Integer>>();
	private int data[] = new int[1000];
	
	private void dfs(TreeNode root, int sum, int cur) {
		if (root == null) return;
		if (root.left == null && root.right == null && root.val == sum) {
			List<Integer> tmp = new ArrayList<Integer>();
			for (int i = 0; i < cur; i++) tmp.add(data[i]);
			tmp.add(sum);
			ans.add(tmp);
			return;
		}
		
		sum -= root.val;
		data[cur] = root.val;
		if (root.left != null) dfs(root.left, sum, cur+1);
		if (root.right != null) dfs(root.right, sum, cur+1);
	}
	
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
    	ans.clear();
    	dfs(root, sum, 0);
    	return ans;
    }
}



LeetCode Path Sum II

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/45618307

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