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

leetcode_113题——Path Sum II(深度优先搜索)

时间:2015-04-24 22:27:17      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

Path Sum II

 Total Accepted: 41402 Total Submissions: 155034My 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]
]

 

 

Hide Tags
 Tree Depth-first Search
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

   这道题采用深度优先搜索的算法来做,由于想记录下从根节点到每个节点的各个节点,所以在用堆栈的时候没有多加了一个向量来存储路径

#include<iostream>
#include<stack>
#include<utility>
#include<vector>
using namespace std;

struct TreeNode {
	     int val;
	     TreeNode *left;
	     TreeNode *right;
	     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
	 };

vector<vector<int> > pathSum(TreeNode *root, int sum) 
{
	vector<vector<int> > result;
	if(root==NULL)
		return result;

	stack<pair<TreeNode*,vector<int> > > sta_temp;
	vector<int> temp;
	temp.push_back(root->val);
	sta_temp.push(make_pair(root,temp));

	vector<int> Vtemp_top;
	TreeNode* Ttemp_top;

	while(!sta_temp.empty())
	{
		Vtemp_top=sta_temp.top().second;
		Ttemp_top=sta_temp.top().first;

		sta_temp.pop();

		if(Ttemp_top->left==NULL&&Ttemp_top->right==NULL)
		{
			int sum_temp=0;
			for(int i=0;i!=Vtemp_top.size();i++)
			{
				sum_temp+=Vtemp_top[i];
			}
			if(sum_temp==sum)
				{
					result.push_back(Vtemp_top);
			    }
	     }
		if(Ttemp_top->left!=NULL)
		{
			Vtemp_top.push_back(Ttemp_top->left->val);
			sta_temp.push(make_pair(Ttemp_top->left,Vtemp_top));
			Vtemp_top.pop_back();
		}
		if(Ttemp_top->right!=NULL)
		{
			Vtemp_top.push_back(Ttemp_top->right->val);
			sta_temp.push(make_pair(Ttemp_top->right,Vtemp_top));
			//temp.pop_back();
		}
     }
	return result;
}

int main()
{
	TreeNode* root=(TreeNode*)malloc(sizeof(TreeNode));
	root->val=1;
	root->right=NULL;
	root->left=(TreeNode*)malloc(sizeof(TreeNode));
	root->left->val=2;
	root->left->left=NULL;
	root->left->right=NULL;

	vector<vector<int> > temp;
	temp=pathSum(root,1);
}

  

leetcode_113题——Path Sum II(深度优先搜索)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4454471.html

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