c代码:二叉树
char* str;
int top;
// 录入子节点前加(
void dfs (struct treenode* root) {
if (root == null) {
return;
}
str[top++] = '(';
// top += sprintf(str + strlen(str), "%d", root->val); // strlen(str)错误,因为后续添加了')', 没有添加'\0';
top += sprintf(str + top, "%d", root->val);
if (root->left == null && root->right != null) { // 提前判断左右节点
str[top++] = '(';
str[top++] = ')';
}
dfs(root->left);
dfs(root->right);
str[top++] = ')';
}
char * tree2str(struct treenode* root){
if (root == null){
return null;
}
str = (char*)malloc(sizeof(char) * 30000);
top = 0;
dfs(root);
str[strlen(str)] = '\0'; // (1(2(4))(3))
char* ans = (char*)malloc(sizeof(char) * top); // 处理细节
for (int i = 1; i < top - 1; ++i) {
ans[i - 1] = str[i];
}
ans[top-2] = '\0';
return ans;
}
发表评论