您的位置:首页 > Web前端

剑指offer:二叉树中和为某一值的路径

2015-11-18 22:51 495 查看


题目描述:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点。

/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
TreeNode * creat()
{
string x;
cin>>x;
int i, num = 0;
if(x.size() > 1)
{
for(i = 0; i < x.size(); i++)
num = num * 10 + x[i] - '0';
}
else
{
if(x[0] == '#')
return NULL;
else
num = x[0] - '0';
}
TreeNode * res = new TreeNode(num);
res->left = creat();
res->right = creat();
return res;
}*/
class Solution {
public:
vector<vector<int> > find(TreeNode* root, int num, vector<int> tmp)
{
vector<vector<int> > res1;
vector<vector<int> > res2;
if(!root)
{
if(!num)
{
res1.push_back(tmp);
}
return res1;
}
tmp.push_back(root->val);
if(!root->left && !root->right)
res1 = find(root->left, num - root->val, tmp);
else
{
res1 = find(root->left, num - root->val, tmp);
res2 = find(root->right, num - root->val, tmp);
}
tmp.pop_back();
res1.insert(res1.end(), res2.begin(), res2.end());
//vector<vector<int> > :: iterator it;
//sort(res1.begin(), res1.end());
//it = unique(res1.begin(), res1.end());
//res1.erase(it, res1.end());
return res1;
}
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vector<vector<int> > res;
vector<int> tmp;
if(!root)
return res;
else
return find(root, expectNumber, tmp);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: