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

前言

个人小记


一、代码

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))
相关推荐
哦吼!1 小时前
数据结构—二叉树(二)
数据结构
码农Cloudy.3 小时前
C语言<数据结构-链表>
c语言·数据结构·链表
lightqjx4 小时前
【数据结构】顺序表(sequential list)
c语言·开发语言·数据结构·算法
田野追逐星光4 小时前
堆的应用(讲解超详细)
数据结构
谭林杰5 小时前
散链表基本操作讲解
数据结构·链表
yi.Ist5 小时前
数据结构 —— 栈(stack)在算法思维中的巧妙运用
开发语言·数据结构
祁思妙想6 小时前
【LeetCode100】--- 1.两数之和【复习回滚】
数据结构·算法·leetcode
橘颂TA6 小时前
【C++】红黑树的底层思想 and 大厂面试常问
数据结构·c++·算法·红黑树
<但凡.7 小时前
数据结构与算法之美:广义表
数据结构·c++·算法
偷偷的卷9 小时前
【算法笔记 day three】滑动窗口(其他类型)
数据结构·笔记·python·学习·算法·leetcode