One of the lunch table discussion....
Node.java
What if I want to store whole binary tree into file?
I said, implement serializable interface for Node and you are good to go, person was not convinced, I have to saw him actual implementation. Here is my sample code. Normally people make assumption that only given node will be stored and not whole tree, which is not true. Serialization takes care of whole tree. Sample code below:
Node.java
package com.java;
import java.io.Serializable;
public class Node implements Serializable {
private static final long serialVersionUID = 1L;
public int data;
public Node left;
public Node right;
public Node(int data, Node left, Node right) {
super();
this.data = data;
this.left = left;
this.right = right;
}
public Node(int data) {
this(data, null, null);
}
public Node() {
super();
}
}
SerializeDeserializeBT.java
package com.java;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class SerializeDeserializeBT implements Serializable {
public static void main(String[] args) {
SerializeDeserializeBT s = new SerializeDeserializeBT();
Node root = s.initBTree();
s.serialize(root);
s.deserialize();
}
public Node initBTree() {
return new Node(80, new Node(60, new Node(50), new Node(70)), new Node(86, new Node(82), new Node(90)));
}
public void serialize(Node root){
try {
FileOutputStream fs = new FileOutputStream("C:\\test.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(root);
os.close();
fs.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void deserialize() {
try {
FileInputStream fis = new FileInputStream("c:\\test.ser");
ObjectInputStream input = new ObjectInputStream(fis);
Node root = (Node) input.readObject();
traverseInOrder(root);
} catch(Exception e) {
e.printStackTrace();
}
}
public void traverseInOrder(Node root) {
if(root != null) {
traverseInOrder(root.left);
System.out.println(root.data + " " );
traverseInOrder(root.right);
}
}
}


