Path Sum II--LeetCode

来源:互联网 发布:意大利 世界杯 知乎 编辑:程序博客网 时间:2024/06/01 15:13

题目:

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]]
思路:多一个记录路径的向量

void helper(BinTree* root,int key,int cur,vector<int>& vec){if(root == NULL)return ;cur+=root->value;vec.push_back(root->value);if(root->left == NULL && root->right == NULL && cur == key){int i;for(i=0;i<vec.size();i++)cout<<vec[i]<<"  ";cout<<endl;}if(root->left !=NULL){helper(root->left,key,cur,vec);vec.pop_back();}if(root->right !=NULL){helper(root->right,key,cur,vec);vec.pop_back();}}void PathSum(BinTree* root,int key){int cur=0;if(root== NULL)return ;vector<int> vec;helper(root,key,cur,vec);}

1 0
原创粉丝点击