您的位置:首页 > 其它

257 Binary Tree Paths

2015-09-25 20:13 260 查看
题意:给定二叉树,找出所有根到叶子的路径

分析: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);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: