Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"]
Explanation: 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 getLength(TreeNode* root,vector<string> &result,string s)
{
if(root==NULL)
return;
if(root->left==NULL&&root->right==NULL)
{
result.push_back(s);
}
if(root->left!=NULL)
{
getLength(root->left,result,s+"->"+to_string(root->left->val));
}
if(root->right!=NULL)
{
getLength(root->right,result,s+"->"+to_string(root->right->val));
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
if(root==NULL)
return result;
getLength(root,result,to_string(root->val));
return result;
}
};