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"]
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
class Solution {
public:
void findPath(vector<string> &vec, TreeNode *node, string path) {
if(node==NULL) return;
if(node!=NULL && node->left==NULL && node->right==NULL) {
path += to_string(node->val);
vec.push_back(path);
return ;
}
path += to_string(node->val);
path += "->";
findPath(vec, node->left, path);
findPath(vec, node->right, path);
}
vector<string> binaryTreePaths(TreeNode *root) {
vector<string> vec;
findPath(vec, root, "");
return vec;
}
}