题目:
你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。
空节点则用一对空括号 “()” 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int count;
void tree(struct TreeNode* root, char* str)
{
if(root){
count += sprintf(str+count, "%d", root->val );
if(root->left||root->right){
count += sprintf(str+count, "%s", "(");
tree(root->left, str);
count += sprintf(str+count, "%s", ")");
}
if(root->right){
count += sprintf(str+count, "%s", "(");
tree(root->right, str);
count += sprintf(str+count, "%s", ")");
}
}
}
char * tree2str(struct TreeNode* t){
char* str = malloc(50000 );
count = 0;
tree(t, str);
str[count++] = '\0';
return str;
}