Uber | Phone screen | Serialize and Deserialize an N-ary Tree

2690
Jun 09, 2018
Jul 20, 2019

I got an interview with Uber for the Android Engineer position. It is an one-hour interview, and I was asked one coding question:

During the coding test, I didn't finish the implementation and got rejected. The interviewer didn't give me any hints when I got stucked, even when I ask him if I am 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 serializd 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.

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<>();
    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;
  }
}
Comments (8)