递归穷举搜索,用一个list当做栈压入并弹出每个节点,用于遍历。

这个套路可以应用到类似的穷举搜索问题上。因为有负有正,所以没办法剪枝。


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void _pathSum(TreeNode *root, int sum, vector<vector<int> > &res, list<int> &s){
		if(root->left==NULL && root->right==NULL){
			if(root->val == sum){
				vector<int> tmp(s.begin(),s.end());
				tmp.push_back(root->val);
				res.push_back(tmp);
			}
			return;
		}
		s.push_back(root->val);
		if(root->left)
			_pathSum(root->left,sum-root->val,res,s);
		if(root->right)
			_pathSum(root->right,sum-root->val,res,s);
		s.pop_back();
	}
	vector<vector<int> > pathSum(TreeNode *root, int sum) {
		vector<vector<int> > res;
		if(!root)
			return res;
		list<int> s;
		_pathSum(root,sum,res,s);
		return res;
	}
};


Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐