How to Serialize Binary Tree

后端 未结 10 901
野的像风
野的像风 2020-12-23 21:09

I went to an interview today where I was asked to serialize a binary tree. I implemented an array-based approach where the children of node i (numbering in level-order trave

10条回答
  •  再見小時候
    2020-12-23 21:42

    How about performing an in-order traversal and putting the root key and all node keys into a std::list or other container of your choice which flattens the tree. Then, simply serialize the std::list or container of your choice using the boost library.

    The reverse is simple and then rebuild the tree using standard insertion to a binary tree. This may not be entirely efficient for a very large tree but runtime to convert the tree into a std::list is O(n) at most and to rebuild the tree is O(log n) at most.

    I am about to do this to serialize a tree I just coded up in c++ as I am converting my database from Java to C++.

提交回复
热议问题