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> v;
void dfs(TreeNode* root,string temp){
if(root->left==NULL&&root->right==NULL){
v.push_back(temp);
return;
}
if(root->left){
dfs(root->left,temp+"->"+to_string(root->left->val));
}
if(root->right){
dfs(root->right,temp+"->"+to_string(root->right->val));
}
}
vector<string> binaryTreePaths(TreeNode* root) {
if(root==NULL) return v;
dfs(root,to_string(root->val));
return v;
}
};
网友评论