Binary Tree Paths
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"]
分析:采用递归遍历,分析左右节点情况,按照题意输出所有情况,C++中int转string
可以采用
stringstream ss;
ss<<(root->val);
string starttempstring=ss.str();
代码:
/**
* 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) {
string starttemp;
vector<string> resultstring;
stringstream ss;
if(root==NULL)
{
return resultstring;
}
ss<<(root->val);
string starttempstring=ss.str();
if(root->left!=NULL)
{
starttemp=starttempstring+"->";
vector<string>tempres;
tempres.clear();
tempres=binaryTreePaths(root->left);
for(int i=0; i<tempres.size();i++)
{
resultstring.push_back(starttemp+tempres[i]);
}
}
if(root->right!=NULL)
{
starttemp=starttempstring+"->";
vector<string>tempres;
tempres.clear();
tempres=binaryTreePaths(root->right);
for(int i=0; i<tempres.size();i++)
{
resultstring.push_back(starttemp+tempres[i]);
}
}
if(root->left==NULL&&root->right==NULL)
{
resultstring.push_back(starttempstring);
}
return resultstring;
}
};