Code前端首页关于Code前端联系我们

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

terry 2年前 (2023-09-27) 阅读数 66 #数据结构与算法

>序列化:必须存储一个中序遍历结果,然后添加一个预序或缺序结果

>反序列化:根据两次遍历产生的结果进行恢复二叉树是以下代码(先序和按顺序):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

```TreeNode* helper(vectorpre,int startPre,int endPre, vectorin,int startIn ,int endIn){

if(startPre>endPre||startIn>endIn)

return nullptr;

TreeNode * root=new TreeNode(❀pre [startPre]);

for(int i =startIn;i = 助手 (pre, startpre+1, startpre+i-startin, i, startin, i -1 );

root->=helper(pre,i-startIn+startPre+1,endPre,in,i+);

}

}

返回根;

}

TreeNode* reConstructBinaryTree(vector ♽),)

TreeNode * root = helper( ♽ ) ,0,pre.size()-1,,) - 1);

归根;

}

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

热门