Serialize and Deserialize Binary Tree(bfs&dfs)

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Example:

You may serialize the following tree:

    1
   / \
  2   3
     / \
    4   5

as 
"[1,2,3,null,null,4,5]"

Clarification:The above format is the same ashow LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

分析

serialize 就是pre order遍历

deserialize就是顺序按照i, 2i+1,2i+2来拼装树。

第一遍以为是level order遍历,居然也过了,好像就是level order的

其实正确string是:[1,2,null,null,3,4,null,null,5,null,null]

RECURSIVE

ser:遇到none则加入‘null, ’ 记得str(root.val)

de:global deque popleft。

BFS

第二遍 preorder dfs

pos作为参数传入 pos+=1始终没用,最后用list.pop(0)才解决

preorder Bfs

用q来存root, left,right弹入弹出。data的val用来for loop every item。

直接建好所有Node和Nonelist, 2个list ,一个for loop,一个用来pop。

preorder dfs

Last updated

Was this helpful?