Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
My code can work:
public static ArrayList<String> Serialize(BinaryTreeNode head){
ArrayList<String> arrayTree=new ArrayList<String>();
serializeProcess(head,arrayTree);
return arrayTree;
}
public static void serializeProcess(BinaryTreeNode head,ArrayList<String> arrayTree){
if(head==null){
arrayTree.add("#");
return;
}
arrayTree.add(String.valueOf(head.value));
serializeProcess(head.leftchild, arrayTree);
serializeProcess(head.rightchild, arrayTree);
}
public static BinaryTreeNode Reconstruct(ArrayList<String> map){
Stack<BinaryTreeNode> holdNode=new Stack<BinaryTreeNode>();
HashMap<BinaryTreeNode,Boolean> definedLeft=new HashMap<BinaryTreeNode,Boolean>();
BinaryTreeNode result=new BinaryTreeNode(Integer.valueOf(map.get(0)));
holdNode.push(result);
for(int i=1;i!=map.size();i++){
BinaryTreeNode current=holdNode.pop();
if(!definedLeft.containsKey(current)){
definedLeft.put(current, true);
if(!map.get(i).equals("#")){
current.leftchild=new BinaryTreeNode(Integer.valueOf(map.get(i)));
holdNode.push(current);
holdNode.push(current.leftchild);
}
else{
holdNode.push(current);
}
}
else{
if(!map.get(i).equals("#")){
current.rightchild=new BinaryTreeNode(Integer.valueOf(map.get(i)));
holdNode.push(current.rightchild);
}
}
}
return result;
}
public ArrayList<Integer> serialize(Pair head)
{
ArrayList<Integer> al = new ArrayList<Integer>();
if(head==null)
{
al.add(null);
return al;
}
Stack<Pair> s = new Stack<Pair>();
s.push(head);
while(!s.empty())
{
Pair node = ( Pair) s.pop();
if(node==null)
{
al.add(null);
}
else
{
s.push(node.second);
s.push(node.first);
al.add(node.val);
}
}
return al;
}
public Pair cons_tree(Iterator<Integer> al)
{
Pair p = new Pair(null, null , 0);
Integer i = al.next();
if(i == null)
{
p = null;
return p;
}
p.val = i;
p.first = cons_tree(al);
p.second = cons_tree(al);
return p;
}
We just need to serialize the binary tree in such a way that when we are de-serializing, we can identify the elements in the right and left subtrees. Thus, we can serialize the pre-order traversal of the tree with a special character ('#' etc.) between the left and right subtree of each node. Also, to make things simple, we can insert another special character ('$' etc.) in place of NULL pointers.
- DeathEater August 06, 2012Now, we can recursively deserialize, since for each tree, we can always identify the root, elements in the left subtree and elements in the right subtree.