二叉树的序列化---广义表

前言

个人小记


一、代码

c 复制代码
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define key(n) (n)?(n->key):(-1)
#define MAX_NODE 10

typedef struct Node
{
    int key;
    struct Node* lchild,*rchild;
}Node;

Node* init_node(int key)
{
    Node* node=(Node* )malloc(sizeof(Node));
    node->key=key;
    node->lchild=node->rchild=NULL;
    return node;
}

Node* insert(Node* root,int key)
{
    if(root==NULL)return init_node(key);
    if(rand()%2)root->lchild=insert(root->lchild,key);
    else root->rchild=insert(root->rchild,key);
    return root;
}

Node* get_tree(int n)
{
    Node* root=NULL;
    for(int i=0;i<n;i++)
    {
        root=insert(root,rand()%100);
    }
    return root;
}


void clear(Node* root)
{
    if(root==NULL)return ;
    clear(root->lchild);
    clear(root->rchild);
    free(root);
    return ;
}

void print(Node* root)
{
    if(root==NULL)return ;
    printf("%d(%d,%d)\n",key(root),key(root->lchild),key(root->rchild));
    print(root->lchild);
    print(root->rchild);
    return ;
}

char buff[1000];
int len;

void __serial(Node* root)
{
    if(root==NULL)return ;
    len+=snprintf(buff+len,100,"%d",root->key);
    if(root->lchild==NULL&&root->rchild==NULL)return ;
    len+=snprintf(buff+len,100,"(");
    __serial(root->lchild);
    if(root->rchild)
    {
        len+=snprintf(buff+len,100,",");
        __serial(root->rchild);
    }
    len+=snprintf(buff+len,100,")");
    return ;
}

void serial(Node* root)
{
    memset(buff,0,sizeof(buff));
    len=0;
    __serial(root);
    return ;
}

int main()
{
    srand((unsigned)time(0));
    Node* root=get_tree(MAX_NODE);
    printf("先序遍历每个节点的信息:\n");
    print(root);
    serial(root);
    printf("广义表序列化:%s\n",buff);
    clear(root);
    return 0;
}

二、测试结果

c 复制代码
先序遍历每个节点的信息:
93(70,52)
70(-1,38)
38(-1,79)
79(58,-1)
58(-1,-1)
52(23,94)
23(67,-1)
67(68,-1)
68(-1,-1)
94(-1,-1)
广义表序列化:93(70(,38(,79(58))),52(23(67(68)),94))
相关推荐
Sarvartha41 分钟前
单链表的顺序建立与结点的删除(期末题复现)
数据结构
Dlrb12112 小时前
数据结构-链表
数据结构·链表·逻辑结构·单向链表·物理结构·valgrind工具
小的~~2 小时前
算法题:只出现一次的数字
数据结构·算法
一切皆是因缘际会2 小时前
从概率拟合到内生心智:七层投影架构重构AGI数字生命新范式
大数据·数据结构·人工智能·重构·架构·agi
历程里程碑2 小时前
56 . 高效ET非阻塞IO服务器设计指南
java·运维·服务器·开发语言·数据结构·c++·排序算法
南境十里·墨染春水2 小时前
数据结构 —— 顺序表
数据结构
tongluowan0073 小时前
数据结构 Bitmap(位图)示例 - 用户签到系统
开发语言·数据结构·bitmap·用户签到系统
洛水水3 小时前
Redis对象类型与底层数据结构
数据结构·数据库·redis
Hesionberger3 小时前
LeetCode114:二叉树展开为链表(三解法)
数据结构
一行代码一行诗++3 小时前
循环的嵌套
数据结构·算法