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

前言

个人小记


一、代码

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))
相关推荐
Nix Lockhart35 分钟前
《算法与数据结构》第七章[算法3]:图的最小生成树
c语言·数据结构·算法
拾光Ծ3 小时前
【C++】STL有序关联容器的双生花:set/multiset 和 map/multimap 使用指南
数据结构·c++·算法
西望云天4 小时前
The 2023 ICPC Asia Shenyang Regional Contest(2023沈阳区域赛CEJK)
数据结构·算法·icpc
zh_xuan4 小时前
LeeCode92. 反转链表II
数据结构·算法·链表·leecode
2401_841495645 小时前
【数据结构】汉诺塔问题
java·数据结构·c++·python·算法·递归·
xxxxxxllllllshi5 小时前
Java 集合框架全解析:从数据结构到源码实战
java·开发语言·数据结构·面试
bawangtianzun8 小时前
重链剖分 学习记录
数据结构·c++·学习·算法
ChoSeitaku12 小时前
NO.14数据结构红黑树|树高|转化4阶B树|插入操作|删除操作
数据结构·b树
T1an-112 小时前
力扣169.多数元素
数据结构·算法·leetcode
violet-lz14 小时前
数据结构:七大线性数据结构从结构体定义到函数实现的的区别
数据结构