606. 根据二叉树创建字符串

606. 根据二叉树创建字符串

606. 根据二叉树创建字符串_第1张图片


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;
}

你可能感兴趣的:(LeetCode刷题,深度优先,算法)