LeetCode-113. 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.

Note: A leaf is a node with no children.

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

题目:这是pathSum的升级,从根到叶子结点,如果和等于sum,则输出这条路径,最后以二维vector的形式返回

思路:刚做完257. Binary Tree Paths这道题后,我的想法很直接,先把二叉树全部转换为二维vector,再判断vector里的每个vector之和是否等于sum,如果是则是符合要求的。写出程序如下:

class Solution {  
public:
    vector<vector<int> > pathSum(TreeNode* root, int sum) {
         vector<vector<int> > temp = TreeToVector(root);
         vector<vector<int> > res;
		 for(int i=0;i<temp.size();i++){
		 	int nn = accumulate(temp[i].begin(),temp[i].end(),0);
		 	if( nn == sum)
		 		res.push_back(temp[i]);
		 }
		 return res;
    }
    vector<vector<int> > TreeToVector(TreeNode* root){
    	vector<vector<int> > res;
    	if(!root)
    		return res;
    	if(root->left==NULL&&root->right==NULL){
    		vector<int> temp;
    		temp.push_back(root->val);
    		res.push_back(temp);
    		return res;
		}
		vector<vector<int> > left = TreeToVector(root->left);
		for(int i=0;i<left.size();i++){
			vector<int> temp;
			temp.push_back(root->val);
			temp.insert(temp.end(),left[i].begin(),left[i].end());
			res.push_back(temp);
		}	
		vector<vector<int> > right = TreeToVector(root->right);
		for(int i=0;i<right.size();i++){
			vector<int> temp;
			temp.push_back(root->val);
			temp.insert(temp.end(),right[i].begin(),right[i].end());
			res.push_back(temp);
		}
		return res;
	} 
};

可以通过,但是明显小路是很低的,只有beats 3%o(╯□╰)o

进一步思考,其实完全不需要这样,只要在我们形成一条路径之后检查是否和为sum,再保存到result中即可。而这样的递归时,当对左右字数进行递归时,其sum的值应该更改为sum-root->val了。因此写出程序如下:

class Solution {  
public:
    vector<vector<int> > pathSum(TreeNode* root, int sum) {
        vector<vector<int> > res;
    	if(!root)
    		return res;
    	if(root->left==NULL&&root->right==NULL){ 
    		vector<int> temp;
    		temp.push_back(root->val);
    		if(accumulate(temp.begin(),temp.end(),0) == sum)
	    		res.push_back(temp);
    		return res;
		}
		vector<vector<int> > left = pathSum(root->left,sum-root->val);
		for(int i=0;i<left.size();i++){
			vector<int> temp;
			temp.push_back(root->val);
			temp.insert(temp.end(),left[i].begin(),left[i].end());
			if(accumulate(temp.begin(),temp.end(),0) == sum)
				res.push_back(temp);
		}	
		vector<vector<int> > right = pathSum(root->right,sum-root->val);
		for(int i=0;i<right.size();i++){
			vector<int> temp;
			temp.push_back(root->val);
			temp.insert(temp.end(),right[i].begin(),right[i].end());
			if(accumulate(temp.begin(),temp.end(),0) == sum)
				res.push_back(temp);
		}
		return res;
    } 
};

通过,beats 70%,这样就正常多了。

猜你喜欢

转载自blog.csdn.net/qq_29303759/article/details/81260731