Binary Tree Paths

Description:

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"]

Code:

  void allPath(TreeNode*root, vector<string>&result, vector<int>&path)
{
if (root==NULL)
return ;
path.push_back(root->val);
if (root->left==NULL && root->right==NULL)
{
//注意这里要用ostringstream将字符串写到流中去,然后用str()函数返回字符串
ostringstream sstr;
for (int i = ; i < path.size()-; ++i)
sstr << path[i]<<"->";
sstr<<path[path.size()-];
result.push_back(sstr.str());
}
else
{
if (root->left)
allPath(root->left, result, path);
if (root->right)
allPath(root->right, result, path);
}
path.pop_back();
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string>result;
vector<int>path;
allPath(root, result,path);
return result;
}
上一篇:SpringBoot(七)-- 启动加载数据


下一篇:MySQL事务以及隔离级别