Find below a binary tree node serializer:
import org.junit.Test; import java.io.*; public class NodeSerializer { private static final char NULL_CHAR = '\0'; private static class Node { int data; Node left; Node right; void print() { System.out.println(data); } static void serialize(Node n, ObjectOutputStream into) throws IOException { if (n == null) { into.writeInt(NULL_CHAR); return; } into.writeInt(n.data); //into.write(DELIMITER); serialize(n.left, into); //into.write(DELIMITER); serialize(n.right, into); } static Node deserialize(ObjectInputStream from) throws IOException { int read = from.readInt(); if (read == NULL_CHAR) { return null; } Node n = new Node(); n.data = read; n.left = deserialize(from); n.right = deserialize(from); return n; } } @Test public void testNodeSerializer() throws IOException { Node n = new Node(); n.data = 100; n.left = new Node(); n.left.data = 200; n.left.left = null; n.left.right = null; n.right = new Node(); n.right.left = null; n.right.data = 500; n.right.right = null; ByteArrayOutputStream baos; ObjectOutputStream os = new ObjectOutputStream(baos = new ByteArrayOutputStream(100)); Node.serialize(n, os); os.flush(); //String s = os.toString(); ObjectInputStream byteArrayInputStream = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); Node node = Node.deserialize(byteArrayInputStream); node.print(); node.left.print(); node.right.print(); } }
Comments