深度搜索从根结点到叶节点的路径,检查 各路径上所有结点的值的和是否为sum
利用vector模拟栈来存储路径
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int> > res;
vector<int> path;//保存路径
int path_value = 0;//当前路径的和
preorder(root,sum,path_value,path,res);
return res;
}
void preorder(TreeNode* node, int& sum,int& path_value,vector<int>& path, vector<vector<int> >& res)
{
if(!node)
return;
path_value += node->val;//当前路径的和加上当前这个结点的值
path.push_back(node->val);//把当前结点加入路径中
if( node->left==nullptr && node->right == nullptr && path_value == sum )
{
res.push_back(path);
}
preorder(node->left,sum,path_value,path,res);
preorder(node->right,sum,path_value,path,res);
//当这个当前的结点的左右子树遍历完后,弹出它
path_value -= node->val;
path.pop_back();
}
};