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

前言

个人小记


一、代码

#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;
}

二、测试结果

先序遍历每个节点的信息:
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. 序列---广义

    2024-05-25 18:23:11       37 阅读
  2. 算法——验证前序序列

    2024-05-25 18:23:11       39 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-25 18:23:11       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-25 18:23:11       101 阅读
  3. 在Django里面运行非项目文件

    2024-05-25 18:23:11       82 阅读
  4. Python语言-面向对象

    2024-05-25 18:23:11       91 阅读

热门阅读

  1. go全部版本下载目录

    2024-05-25 18:23:11       32 阅读
  2. C++

    2024-05-25 18:23:11       33 阅读
  3. C语言中的指针第2篇

    2024-05-25 18:23:11       27 阅读
  4. pillow学习2

    2024-05-25 18:23:11       27 阅读
  5. Gin框架HTML文件的加载与渲染

    2024-05-25 18:23:11       33 阅读
  6. 520表白html5爱心代码

    2024-05-25 18:23:11       32 阅读
  7. 常见端口号

    2024-05-25 18:23:11       26 阅读
  8. 使用.net core 调用C#WebService的三种方式

    2024-05-25 18:23:11       34 阅读
  9. kafka之consumer参数auto.offset.reset

    2024-05-25 18:23:11       35 阅读