给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
代码实现:
/**
* 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:
void preorder(TreeNode* node,int &path_val,vector<int> &path,vector<vector<int> > &result,int &sum)
{
if(!node)
return ;
path_val += node->val;
path.push_back(node->val);
if(node->left==NULL && node->right == NULL && path_val == sum)
{
result.push_back(path);
}
preorder(node->left,path_val,path,result,sum);
preorder(node->right,path_val,path,result,sum);
path_val -= node->val;
path.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
int path_val = 0;
vector<vector<int> >result;
vector<int> path;
preorder(root,path_val,path,result,sum);
return result;
}
};
原文地址:https://blog.51cto.com/14472348/2473108
时间: 2024-11-08 15:22:07