题意:给定二叉树,找出所有根到叶子的路径
分析: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:
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);
}
};