您的位置:首页 > 其它

Binary Tree Paths

2015-09-04 17:35 344 查看
Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

1
/   \
2     3
\
5


All root-to-leaf paths are:
["1->2->5", "1->3"]

#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;

};

struct TreeNode *newNode(int data)
{
struct TreeNode *node = (struct TreeNode *)malloc(sizeof(struct TreeNode));
node->val = data;
node->left = NULL;
node->right = NULL;
return (node);
}
class Solution {
public:
vector<string> res;
string s;
vector<string> binaryTreePaths(TreeNode* root)
{
if (root == NULL)
return res;

if (!root->left&& !root->right)
{
s.append(to_string(root->val));
res.push_back(s);
return res;
}

help_paths(root, s, res);

return res;

}

void help_paths(TreeNode *root, string &s, vector<string> &res)
{
if (root->left == NULL && root->right == NULL)
{
s.append(to_string(root->val));
res.push_back(s);
return;
}

s.append(to_string(root->val));
s.push_back('-');
s.push_back('>');
if (root->left)
{

help_paths(root->left, s, res);
int i = s.size() - 1;
for (; i >= 0; i--)
{
if (s[i] == '>')
break;
}
if (i+1<s.size())
s.erase(s.begin()+1+i, s.end());
}
if (root->right)
{

help_paths(root->right, s, res);
int j = s.size() - 1;

for (; j >= 0; j--)
{
if (s[j] == '>')
{
break;
}
}
if (j + 1<s.size())
s.erase(s.begin()+1+j, s.end());
}

int j = s.size() - 1;
int count = 0;
for (; j >= 0; j--)
{
if (s[j] == '>')
{
count++;
if (count==2)
break;
}
}
if (j + 1<s.size())
s.erase(s.begin() + 1 + j, s.end());
return;

}
};

int main(int argc, char *argv[])
{

struct TreeNode *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(7);

vector<string> m;
Solution test;
m=test.binaryTreePaths(root);

for (int i = 0; i < m.size(); ++i)
{
cout << m[i] << endl;
}

return 0;
}


[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: