|
|
Serialisierung
A02.cs
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Node {
public int val;
public Node left, right;
public Node(int x) { val = x; }
}
[Serializable]
class BinaryTree {
Node root = null;
public void Insert(int x) {
Node p = root, father = null;
while (p != null) {
father = p;
if (x < p.val) p = p.left; else p = p.right;
}
p = new Node(x);
if (root == null) root = p;
else if (x < father.val) father.left = p;
else father.right = p;
}
public bool Contains(int x) {
Node p = root;
while (p != null) {
if (p.val == x) return true;
else if (x < p.val) p = p.left;
else p = p.right;
}
return false;
}
private void P(Node p) {
if (p != null) {
P(p.left);
Console.WriteLine(p.val);
P(p.right);
}
}
public void Print() {
P(root);
}
}
public class Test {
public static void Main(string[] arg) {
// Initialization of the tree
BinaryTree tree = new BinaryTree();
foreach (string num in arg)
tree.Insert(Convert.ToInt32(num));
// Serialization
FileStream s = new FileStream("out.txt", FileMode.Create);
IFormatter f = new BinaryFormatter();
f.Serialize(s, tree);
s.Close();
// Deserialization
s = new FileStream("out.txt", FileMode.Open);
BinaryTree tree1 = f.Deserialize(s) as BinaryTree;
s.Close();
if (tree1 != null) tree1.Print();
}
}
|
|