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

前言

个人小记


一、代码

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))
相关推荐
WilliamHu.2 分钟前
A2A协议
java·数据结构·算法
Remember_99317 分钟前
【数据结构】Java数据结构深度解析:栈(Stack)与队列(Queue)完全指南
java·开发语言·数据结构·算法·spring·leetcode·maven
鱼很腾apoc18 分钟前
【实战篇】 第13期 算法竞赛_数据结构超详解(上)
c语言·开发语言·数据结构·学习·算法·青少年编程
嘿嘿嘿x321 分钟前
Modbus TCP 数据结构(发送和返回/读/写)
数据结构·网络协议·tcp/ip
tobias.b39 分钟前
408真题解析-2009-42-数据结构-单链表与双指针技巧
数据结构·计算机考研·408真题解析
666HZ66641 分钟前
数据结构3.0 栈、队列和数组
开发语言·数据结构·算法
tobias.b1 小时前
408真题解析-2009-41-数据结构-最短路径
数据结构·算法·计算机考研·408考研·408真题解析
星火开发设计1 小时前
循环结构进阶:while 与 do-while 循环的适用场景
java·开发语言·数据结构·学习·知识·循环
闪电麦坤952 小时前
Leecode热题100:缺失的第一个正数(数组)
数据结构·算法·leetcode
晚风吹长发12 小时前
初步了解Linux中的动静态库及其制作和使用
linux·运维·服务器·数据结构·c++·后端·算法