保存二叉树到文件文件、二叉树

2023-09-11 05:02:51 作者:上进心@

我有一个非平衡的(不是二进制搜索)二叉树 需要在code(以及后来的德code)到txt文件。 我怎样才能做到这一点在有效的方式?

I have a non-balanced (not binary-search) binary tree Need to incode (and later decode) it to txt file. How can I do it in efficient way?

我发现这个链接 其中谈到了类似的(相同的)的问题,但很明显,我

I found this link which talks about similar (same) problem,but it is obvious for me

推荐答案

请看的这对LEET code 。

我喜欢这样的解决方案,因为它是相对有效的,并产生光输出的文件。

I like this solution because it's relatively efficient and produces light output files.

假设你有一棵树是这样的:

Assuming that you've got a tree like this:

    _30_ 
   /    \    
  10    20
 /     /  \ 
50    45  35

该解决方案允许它,你序列化到这样的输出文本文件:

This solution lets you serialize it to such an output text file:

30 10 50 # # # 20 45 # # 35 # #

要做到这一点,足以通过树进行简单的pre序遍历:

To do this it's enough to perform simple pre-order traversal through the tree:

void writeBinaryTree(BinaryTree *p, ostream &out) {
  if (!p) {
    out << "# ";
  } else {
    out << p->data << " ";
    writeBinaryTree(p->left, out);
    writeBinaryTree(p->right, out);
  }
}

正如你所看到的,符号是用来重新present空节点。

As you can see, a # symbol is used to represent the null node.

要反序列化这个字符串转换成一棵树,你可以使用:

To deserialize this string into a tree you can use:

void readBinaryTree(BinaryTree *&p, ifstream &fin) {
  int token;
  bool isNumber;
  if (!readNextToken(token, fin, isNumber)) 
    return;
  if (isNumber) {
    p = new BinaryTree(token);
    readBinaryTree(p->left, fin);
    readBinaryTree(p->right, fin);
  }
}

正如我前面所说,这种方法产生二叉树的轻量级重新presentation。

As I said before, this method produces a lightweight representation of Binary Tree.

当然,它有一个严重的缺陷:它需要一个符号来重新present空节点

Of course it has one serious drawback: it requires a symbol to represent the null node.

有可能会导致潜在的问题,如果树的节点是一个可以包含本符号本身的字符串。

It can cause potential problems if the nodes of tree are strings that can contain this symbol itself.