栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

手写代码:二叉树序列化反序列化?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

手写代码:二叉树序列化反序列化?

参考回答:

> 序列化:必须保存一个中序遍历结果,然后外加一个前序或者后序遍历结果

>反序列化:根据两次遍历生成的结果恢复二叉树,代码如下(前序和中序):

TreeNode* helper(vector<int>pre,int startPre,int endPre,vector<int>in,int startIn,int endIn){    if(startPre>endPre||startIn>endIn)    return nullptr;    TreeNode * root=new TreeNode(pre[startPre]);    for(int i=startIn;i<=endIn;++i)    {        if(in[i]==pre[startPre])      {    root->left=helper(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);    root->right=helper(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);    break;      }    }    return root;    }    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin)    {    TreeNode *root=helper(pre,0,pre.size()-1,vin,0,vin.size()-1);    return root;}}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/366475.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号