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

leetcode_113_Path Sum II

时间:2015-03-07 14:15:19      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   tree   dfs   

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


Path Sum II

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


class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int> > ans;
		vector<int> temp;
		if (root!=NULL)
			pathSumUtil(root , sum , 0 , ans , temp);
		return ans;
    }
private:
	
	void pathSumUtil(TreeNode *root, int sum , int cur , vector<vector<int> > &ans , vector<int> &temp)
	{
		temp.push_back(root->val);
		if(root->left==NULL && root->right==NULL)
		{
			if( cur+root->val == sum )
				ans.push_back(temp);
		}
		else
		{
			if(root->left!=NULL)
				pathSumUtil( root->left, sum, cur+root->val, ans , temp );
			if(root->right!=NULL)
				pathSumUtil( root->right, sum, cur+root->val, ans , temp );
		}
	    temp.pop_back();
	}
};


leetcode_113_Path Sum II

标签:leetcode   c++   tree   dfs   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/44115267

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