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"]
/**
* 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 helper(vector<string> &svec, string s, TreeNode *root)
{
if(root -> left == NULL && root -> right == NULL)
{
int t = root -> val;
char p[256];
sprintf(p, "%d", t);
s += p;
svec.push_back(s);
}
int t = root -> val;
char p[256];
sprintf(p, "%d", t);
s += p;
if(root -> left)
{
helper(svec, s + "->", root -> left);
}
if(root -> right)
{
helper(svec, s + "->", root -> right);
}
}
vector<string> binaryTreePaths(TreeNode* root)
{
vector<string> svec;
if(root == NULL)
{
return svec;
}
helper(svec, "", root);
return svec;
}
};