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"]
Nothing special.... Just follow binary tree recursive.
static void binaryTreePaths(TreeNode* root, vector<string>& res, string path) {
if(!root) return;
if(!root->left && !root->right) {
path += to_string(root->val);
res.push_back(path);
return;
}
binaryTreePaths(root->right, res, path + to_string(root->val) + "->");
binaryTreePaths(root->left, res, path + to_string(root->val) + "->");
}
vector<string> binaryTreePaths(TreeNode* root) {
if(!root) return {};
vector<string> res;
string path = "";
binaryTreePaths(root, res, path);
return res;
}