257. Binary Tree Paths
1.这道题,一开始使用find_last_of的时候,想要匹配 ‘-‘,但是val可以是负数,所以匹配错误。
2.整型转化为字符串的方法:利用stringstream
stringstream ss;
ss << root->val;
string rval = ss.str();
class BinaryTreePaths {
public:
vector<string> binaryTreePaths(TreeNode* root) {
if (root == NULL)
{
return vector<string>();
}
stringstream ss;
ss << root->val;
string rval = ss.str();
curStr += rval;
if (root->left == NULL && root->right == NULL)
{
res.push_back(curStr);
return res;
}
if (root->left != NULL)
{
binaryTreePathsCore(root->left);
}
if (root->right != NULL)
{
binaryTreePathsCore(root->right);
}
return res;
}
void binaryTreePathsCore(TreeNode* root)
{
stringstream ss;
ss << root->val;
string rval = ss.str();
curStr += "->" + rval;
if (root->left == NULL && root->right == NULL)
{
res.push_back(curStr);
// erase
string::size_type idx = curStr.find_last_of('>');
curStr.erase(idx - 1);
return ;
}
if (root->left != NULL)
{
binaryTreePathsCore(root->left);
}
if (root->right != NULL)
{
binaryTreePathsCore(root->right);
}
string::size_type idx = curStr.find_last_of('>');
curStr.erase(idx - 1);
}
string curStr;
vector<string> res;
};