Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
dfs,思路参考这里
/**
* 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:
void dfs(vector<string>&ans,TreeNode* root,string s){
if(!root->left&&!root->right){
ans.push_back(s);
return;
}
if(root->left){
dfs(ans,root->left,s+"->"+to_string(root->left->val));
}
if(root->right){
dfs(ans,root->right,s+"->"+to_string(root->right->val));
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string>ans;
if(!root){
return ans;
}
dfs(ans,root,to_string(root->val));
return ans;
}
};