serialize and deserialize a tree

serialize, ie, convert the object to a byte stream to transfer it through networking, de-seralize, re-construct the object by give output stream. here is the implementation

serialize :

public static void serialize( OutputStream out, Node node )
{
    if( node == null )
    {
        out.write( "()" );
    }
    else
    {
        out.write( "(" );
        out.write( node.data + "" );
        // recursive call
        serialize( out, node.left );
        serialize( out, node.right );
        out.write( ") );
    }
}

de-serialize:

public static Node deSerialize( BufferedInputStream reader ) throw IOException
{
    char c = ( char ) reader.read( );
    if( c == '(' )
    {
        c = ( char ) reader.read( );
        // there is no data, since the node is null
        if( c == ')' )
        {
            return null;
        }
        StringBuffer sb = new StringBuffer( );
        while(  c != ')' )
        {
            sb.append( c );
            c = ( char ) reader.read( );
        }

        Node newNode = new Node( sb.toString() );
        if( c == '( ' )
        {
            reader.reset( );
            newNode.left = deSerialize( reader );
            newNode.right = deSerialize( reader );
        }
    }
    return newNode;
}

Advertisements
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s