7.Binary Tree Serialization

1.Desciption(Medium)

Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.

Notice

There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output ofserializeas the input ofdeserialize, it won't check the result of serialize.

Example

An example of testdata: Binary tree{3,9,20,#,#,15,7}, denote the following structure:

  3
 / \
9  20
  /  \
 15   7

Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.

You can use other method to do serializaiton and deserialization.

2.Code

serialize: 树变序列:用一个stringbuilder ,每次append进去元素和逗号,最后再把最后一个逗号去掉。

deserialize序列变树,开始先用substring和split把{}和,去掉,是他们变成一个数组,再进入队列,注意没poll一个元素要先判断是不是空再进行下面的操作。用一个Index来控制读取数组的哪个值。

Last updated

Was this helpful?