Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
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:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if(root==nullptr)
return res;
string path=to_string(root->val);
if(root->left!=nullptr)
help(res,root->left,path);
path=to_string(root->val);
if(root->right!=nullptr)
help(res,root->right,path);
if(root->left==nullptr&&root->right==nullptr){
res.push_back(path);
}
return res;
}
void help(vector<string>&res,TreeNode* root,string&path){
int sz=path.size();
string number=to_string(root->val);
path+="->";path+=number;
if(root->left==nullptr&&root->right==nullptr){
res.push_back(path);
path.resize(sz);
return;
}
if(root->left!=nullptr)
help(res,root->left,path);
if(root->right!=nullptr)
help(res,root->right,path);
path.resize(sz);
}
};