Take a look at LeetCode .
I like this solution because it is relatively efficient and creates files with easy output.
Assuming you have a tree like this:
_30_
/ \
10 20
/ / \
50 45 35
This solution allows you to serialize it into such an output text file:
30 10 50 # # # 20 45 # # 35 # #
To do this, it is enough to perform a simple preliminary 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);
}
}
, # node.
, :
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);
}
}
, .
, : node .
, , .