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) {
vector<string> res;
if(!root)
return res;
dfs(root,res,to_string(root->val));
return res;
}
void dfs(TreeNode* root,vector<string>& res,string path)
{
if(!root->left && !root->right)
{
res.push_back(path);
//return ;
}
if(root->left)
dfs(root->left,res,path+"->"+to_string(root->left->val));
if(root->right)
dfs(root->right,res,path+"->"+to_string(root->right->val));
}
};