问题描述:
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"]
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root,vector<string>&path,string s)
{
if(root->left == NULL && root->right == NULL)
{
path.push_back(s);
return path;
}
if(root->left != NULL)
binaryTreePaths(root->left,path,s+"->"+to_string(root->left->val));
if(root->right != NULL)
binaryTreePaths(root->right,path,s+"->"+to_string(root->right->val));
return path;
}
vector<string> binaryTreePaths(TreeNode* root)
{
vector<string>path;
if(root == NULL)
return path;
return binaryTreePaths(root,path,to_string(root->val));
}
};