思路
前序遍历
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<string> result;
void travel(TreeNode* cur, vector<int>& path)
{
int i;
if(cur == NULL)
{
return;
}
path.push_back(cur->val);
if(cur->left == NULL && cur->right == NULL)
{
string temp;
//
for(i = 0; i < path.size()-1; i++)
{
temp.append(to_string(path[i]) + "->");
}
temp.append(to_string(path[i]));
result.push_back(temp);
}
if(cur->left)
{
travel(cur->left, path);
path.pop_back();
}
if(cur->right)
{
travel(cur->right, path);
path.pop_back();
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<int> path;
if(root == NULL)
{
return result;
}
travel(root, path);
return result;
}
};