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

前言

个人小记


一、代码

#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))
  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值