二叉树的广义表反序列化

前言

个人小记


一、代码

#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_NODE 10
#define MAX_LEN 100
#define key(n)(n)?(n->key):(-1)
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* getnewtree(Node* root,int n)
{
    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 ;
}

char buff[MAX_LEN];
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 ;
}

void output(Node* root)
{
    if(root==NULL)return ;
    printf("%d(%d,%d)\n",key(root),key(root->lchild),key(root->rchild));
    output(root->lchild);
    output(root->rchild);
}

Node* diserial(char buff[],int n)
{
    Node* root=NULL;
    Node* p=NULL;
    int top=-1,state=0,fag=0;
    Node** stack=(Node**)malloc(sizeof(Node*)*MAX_NODE);
    for(int i=0;i<n;i++)
    {
        switch(state)
        {
            case 0:
            {
                if(buff[i]<='9'&&buff[i]>='0')state=1;
                if(buff[i]=='(')state=2;
                if(buff[i]==',')state=3;
                if(buff[i]==')')state=4;
                i--;
            }break;
            case 1:
            {
                int key=0;
                while(buff[i]<='9'&&buff[i]>='0')
                {
                    key=key*10+(buff[i]-'0');
                    i++;
                }
                p=init_node(key);
                if(fag==0&&top>=0)stack[top]->lchild=p;
                if(fag==1&&top>=0)stack[top]->rchild=p;
                i--;
                state=0;
            }break;
            case 2:
            {
                stack[++top]=p;
                fag=0;
                state=0;
            }break;
            case 3:
            {
                fag=1;
                state=0;
            }break;
            case 4:
            {
                root=stack[top--];
                state=0;
            }break;
        }
    }
    free(stack);
return root;
}

int main()
{
    srand((unsigned)time(0));
    Node* root=NULL;
    root=getnewtree(root,MAX_NODE);
    serial(root);
    output(root);
    printf("广义表为:\n");
    printf("%s\n",buff);
    Node* new_root=diserial(buff,len);
    printf("反序列化结果为:"\n);
    output(new_root);
    clear(root);
    clear(new_root);
    return 0;
}

二、结果

10(35,0)
35(41,2)
41(-1,25)
25(-1,-1)
2(-1,-1)
0(94,79)
94(65,-1)
65(-1,-1)
79(44,-1)
44(-1,-1)
广义表为:
10(35(41(,25),2),0(94(65),79(44)))
反序列化结果为:
10(35,0)
35(41,2)
41(-1,25)
25(-1,-1)
2(-1,-1)
0(94,79)
94(65,-1)
65(-1,-1)
79(44,-1)
44(-1,-1)
  • 17
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二叉树的序列化是指将二叉树转换为一个字符串,以便存储或传输。二叉树反序列化是指将序列化后的字符串转换为原始二叉树。 对于二叉树的序列化,可以采用前序遍历或层序遍历的方式。以下是使用前序遍历实现二叉树的序列化: 1. 将根节点的值转换为字符串,并将其添加到序列化字符串中。 2. 递归地对左子树进行序列化,将其返回的字符串添加到序列化字符串中。 3. 递归地对右子树进行序列化,将其返回的字符串添加到序列化字符串中。 以下是使用前序遍历实现二叉树反序列化: 1. 将序列化字符串按照逗号分隔符进行拆分,得到一个字符串数组。 2. 从字符串数组中取出第一个元素作为根节点的值,并将其从数组中删除。 3. 创建一个新的节点,并将其值设置为根节点的值。 4. 递归地对左子树进行反序列化,将其返回的节点设置为新节点的左子节点。 5. 递归地对右子树进行反序列化,将其返回的节点设置为新节点的右子节点。 6. 返回新节点。 以下是使用 Python 实现二叉树的序列化和反序列化: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Codec: def serialize(self, root: TreeNode) -> str: if not root: return "" res = str(root.val) left = self.serialize(root.left) right = self.serialize(root.right) if left: res += "," + left if right: res += "," + right return res def deserialize(self, data: str) -> TreeNode: if not data: return None nodes = data.split(",") return self.buildTree(nodes) def buildTree(self, nodes): if not nodes: return None val = int(nodes.pop(0)) root = TreeNode(val) root.left = self.buildTree(nodes) root.right = self.buildTree(nodes) return root ``` 使用前序遍历序列化二叉树,例如: ```python root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.right.left = TreeNode(4) root.right.right = TreeNode(5) codec = Codec() serialized = codec.serialize(root) print(serialized) # "1,2,,3,,4,,5," ``` 使用前序遍历反序列化二叉树,例如: ```python deserialized = codec.deserialize(serialized) print(deserialized.val) # 1 print(deserialized.left.val) # 2 print(deserialized.right.val) # 3 print(deserialized.right.left.val) # 4 print(deserialized.right.right.val) # 5 ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值