采用前序遍历把一个二叉树转换成由括号和整数组成的字符串
/**
* 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:
void TREESTR(TreeNode *t,string &str)
{
if(nullptr==t)
{
return ;
}
char s[30];
sprintf(s,"%d",t->val);
str+=s;
if(nullptr==t->left)
{
if(nullptr==t->right)
{
return;
}
else
{
str.push_back('(');
str.push_back(')');
}
}
else
{
str.push_back('(');
TREESTR(t->left,str);
str.push_back(')');
}
if(nullptr==t->right)
{
return;
}
else
{
str.push_back('(');
TREESTR(t->right,str);
str.push_back(')');
}
}
string tree2str(TreeNode* t) {
string str;
TREESTR(t,str);
return str;
}
};