首页 > 其他 > 详细

Leetcode Path sum II

时间:2014-02-22 14:03:44      阅读:326      评论:0      收藏:0      [点我收藏+]

Path Sum II

 Total Accepted: 6531 Total Submissions: 24225My Submissions

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]
]

就是递归回溯法的应用。2到3星难度。

如下程序:

vector<vector<int> > pathSum(TreeNode *root, int sum) 
	{
		vector<vector<int> > rs;
		vector<int> tmp;
		storeSums(rs, tmp, root, sum);
		return rs;
	}
	void storeSums(vector<vector<int> > &rs, vector<int> &tmp, TreeNode *r, int sum)
	{
		if (!r) return;
		tmp.push_back(r->val);
		storeSums(rs, tmp, r->left, sum - r->val);
		storeSums(rs, tmp, r->right, sum - r->val);
		if (!r->left && !r->right && r->val == sum) rs.push_back(tmp);
		tmp.pop_back();
	}

下面这样写法可以说是很多递归回溯程序的标准形式了:

//2014-2-17 update
	vector<vector<int> > pathSum(TreeNode *root, int sum) 
	{
		vector<vector<int> > rs;
		vector<int> tmp;
		path(rs, tmp, root, sum);
		return rs;
	}
	void path(vector<vector<int> > &rs, vector<int> &tmp, TreeNode *r, int sum)
	{
		if (!r) return;
		if (!r->left && !r->right)
		{
			if (r->val == sum)
			{
				rs.push_back(tmp);
				rs.back().push_back(sum);
			}
			return;
		}
		tmp.push_back(r->val);
		path(rs, tmp, r->left, sum - r->val);
		path(rs, tmp, r->right, sum - r->val);
		tmp.pop_back();
	}


Leetcode Path sum II

原文:http://blog.csdn.net/kenden23/article/details/19330875

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