题意:给定一棵树,求出所有根到叶子节点的路径。
分析:DFS。(注意int到string的转换)
代码:
/**
* 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> ans;
//if(root==nullptr) return ans;
string curPath="";
dfs(ans,curPath,root);
return ans;
}
string getstring ( const int n ){
std::stringstream newstr;
newstr<<n;
return newstr.str();
}
void dfs(vector<string> &paths,string curPath,TreeNode* root){
if(root==nullptr) return;
if(root->left==nullptr&&root->right==nullptr){
paths.push_back(curPath+getstring(root->val));
return;
}
dfs(paths,curPath+getstring(root->val)+"->",root->left);
dfs(paths,curPath+getstring(root->val)+"->",root->right);
}
};