Uber | Phone screen | Serialize and Deserialize an N-ary Tree
Company: Uber
Role: Android Engineer
Interview Stage: Phone screen
Location: unknown
Year: unknown
Original Post Content:
I got an interview with Uber for the Android Engineer position. It is a one-hour interview, and I was asked one coding question:
https://leetcode.com/problems/serialize-and-deserialize-n-ary-tree (premium)
During the coding test, I didn't finish the implementation and got rejected. The interviewer didn't give me any hints when I got stuck, even when I asked him if I was in the right direction. After the interview, I tried it again and solved this problem. In conclusion, I think it is a good coding question for practice.
My Solution
It is important to find a good output format of the serialized tree. Since for each node we don't know the size of its children, we have to keep track of the size.
For example, output = "1#3,2#3,3#0,4#2,5#0,6#0,7#0,8#0,9#0"
In serialization() / deserialization(), we use BFS or DFS to traverse every node. But in my opinion DFS is much easier than BFS.
java
class Solution{
class TreeNode {
int val;
TreeNode[] children;
TreeNode(int v, int size){
this.val = v;
this.children = new TreeNode[size];
}
}
private String serialization(TreeNode root){
StringBuilder sb = new StringBuilder();
serialization(root, sb);
if(sb.length() > 0) sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
private void serialization(TreeNode node, StringBuilder sb){
if(node == null) return;
sb.append(node.val + "#" + node.children.length + ",");
for(TreeNode n : node.children){
serialization(n, sb);
}
return;
}
private TreeNode deserialization(String str){
String[] strs = str.split(",");
LinkedList<String> list = new LinkedList<String>();
for(String s: strs) list.add(s);
return deserialization(list);
}
private TreeNode deserialization(LinkedList<String> list){
String str = list.removeFirst();
String[] s = str.split("#");
TreeNode node = new TreeNode(
Integer.valueOf(s[0]),
Integer.valueOf(s[1]));
for(int i = 0; i < node.children.length; i++){
node.children[i] = deserialization(list);
}
return node;
}
}