Given a binary tree, return all root-to-leaf paths.
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
void helper(TreeNode* node, string cur, vector<string>& res) {
if (!node->left && !node->right) {
cur += to_string(node->val);
res.push_back(cur);
return;
}
cur += to_string(node->val) + "->";
if (node->left) helper(node->left, cur, res);
if (node->right) helper(node->right, cur, res);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if (!root) return res;
string cur;
helper(root, cur, res);
return res;
}
void helper(TreeNode* node, string cur, vector<string>& res) {
if (!node->left && !node->right) {
res.push_back(cur);
return;
}
if (node->left) helper(node->left, cur + "->" + to_string(node->left->val), res);
if (node->right) helper(node->right, cur + "->" + to_string(node->right->val), res);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> res;
if (!root) return res;
string cur = to_string(root->val);
helper(root, cur, res);
return res;
}