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:
vector<string> binaryTreePaths(TreeNode* root) {
if (root == NULL){
return res;
}
vector<int> path;
helper(root, path);
return res;
}
private:
void helper(TreeNode* root, vector<int>& path){
path.push_back(root->val);
if (root->left == NULL&&root->right == NULL){
string p;
int len = path.size();
for (int i = 0; i < len; i++){
if (i != len - 1){
p += to_string(path[i]);
p += "->";
}
else{
p += to_string(path[i]);
}
}
res.push_back(p);
}
if (root->left){
helper(root->left, path);
}
if (root->right){
helper(root->right, path);
}
path.pop_back();
}
vector<string> res;
};