VMWare Inc Interview Question
Member Technical StaffsCountry: India
Interview Type: In-Person
I think at first we should understand the question, as we know, a binary tree has three traverse orders, using anyone we can get an order, we can also call this order as one serialization of the binary tree.
And you know if we know the order of
1) inorder and preorder or 2) inorder and postorder we can construct a binary tree,
if we only know the preorder and postorder, we can't construct a binary tree, I don't know whether the question has some relationship with this knowledge.
But in my opinion, to serialize or deserialize a Binary tree, the operations all need a order of the Binary tree's elements.
In OCaml, to JSON :
type 'a binary_tree = Sheet of 'a | Node of 'a binary_tree * 'a binary_tree ;;
let rec serialize serialize_generic_type tree =
let serial = serialize serialize_generic_type in
let first = "{ " in
let last = " }" in
let str = match tree with
| Sheet a -> "sheet : "^(serialize_generic_type a)^","
| Node (a, b) -> "node : { elem1 : "^(serial a)^", elem2 : "^(serial b)^"}" in
first^str^last;;
let string_of_char = String.make 1;;
let serialize_char c = "'"^(string_of_char c)^"'";;
let b = Node (Sheet 'v', Node (Sheet 'a', Sheet 'c'));;;;
(* Results *)
serialize serialize_char b;;
(* - : string = "{ node : { elem1 : { sheet : 'v', }, elem2 : { node : { elem1 : { sheet : 'a', }, elem2 : { sheet : 'c', }} }} }" *)
If we use inorder + preorder/postorder, we are need to transfer/store each node twice.
if node size is large then we could have large redundant data.
If we have pre-order traversal and we have no. of node in left sub child tree at each node, then we can create binary tree from pre-order only.
lets write grammar for tree
Head := header . tree
header := size of each node . no of nodes in tree .
tree := no_of_left_child . root_node. post-order of left tree. post-order of right tree.
Serialize is easy just do a preorder traversal and remember to note N as null nodes. lets say a tree gives
12N4NN35NNN
on preorder traversal.
Here is code to construct tree back.
public int construct(Node parent, char[] arr,int i , boolean left){
int ret = -1;
if(i < arr.length){
if(root != null){
if(arr[i] != 'N'){
Node n = new Node(arr[i]);
if(left){
parent.left = n;
}else{
parent.right = n;
}
int j = construct(n, arr, i+1, true);
ret = construct(n, arr, j+1, false);
}else{
ret = i;
}
}else{
root = new Node(arr[i]);
int j = construct(root,arr,i+1,true);
ret = construct(root,arr,j+1,false);
}
}
return ret;
}
We can send inorder and preorder/postorder and reconstruct it.....
- srinu May 06, 2013Also we can do it with only preorder /levelorder traversal with making empty nodevalues as some special characters.
Nice explaination :
leetcode.com/2010/09/serializationdeserialization-of-binary dot html