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

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


C代码:二叉树

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;
}
相关推荐
测绘第一深情21 小时前
MapQR:自动驾驶在线矢量化高精地图构建的端到端 SOTA 方法
数据结构·人工智能·python·神经网络·算法·机器学习·自动驾驶
Magic--21 小时前
C++ 智能指针
开发语言·c++·算法
Timer@21 小时前
LangChain 教程 05|模型配置:AI 的大脑与推理引擎
人工智能·算法·langchain
sali-tec21 小时前
C# 基于OpenCv的视觉工作流-章50-霍夫找圆
图像处理·人工智能·opencv·算法·计算机视觉
想带你从多云到转晴1 天前
04、数据结构与算法---双向链表
java·数据结构·算法·链表
穿条秋裤到处跑1 天前
每日一道leetcode(2026.04.11):三个相等元素之间的最小距离 II
算法·leetcode
Lsk_Smion1 天前
Hot100(开刷) 之 长度最小的数组--删除倒数第N个链表--层序遍历
java·数据结构·算法·kotlin
luoganttcc1 天前
dim3 grid_size(2, 3, 4); dim3 block_size(4, 8, 4)算例
算法
WBluuue1 天前
Codeforces 1088 Div1+2(ABC1C2DEF)
c++·算法
像素猎人1 天前
map<数据类型,数据类型> mp和unordered_map<数据类型,数据类型> ump的讲解,蓝桥杯OJ4567最大数目
c++·算法·蓝桥杯·stl·map