QuadTree Serialization/Deserialization

class QuadTreeNode{
  QuadTreeNode[] children;
  int val;
  public QuadTreeNode(int val) {
   this.val = val;
  children = new QuadTreeNode[4];
  }
}
//为了简化,这里把Tree序列化成一个List这里 Object可以自己定义.
//如果需要字符串,则直接用toString方法, 很容易把它序列化成string,
class SerDeser {
   public List serialize(QuadTreeNode root) {
     List ans = new ArrayList<>();
     serHelper(root, ans);
     return ans; 
  }
  public void serHeper(QuadTreeNode node, List ans) {
     if (node == null) return;
     Tuple t = new Tuple(val);
     ans.add(t);
     
     for (int i = 0; i < 4; i++) {
        if (node.children[I] != null) {
          t.state += (1 << i);
          serHelper(node.children[i], ans)
        }
     }
  }
  public QuadTreeNode deserialize(List list) {
    int[] index = new int[1];
    return deserHelper(list, index);
  } 
  private QuadTreeNode deserHelper(List list, int[] index) {
    if (index[0] >= list.size()) return null;
    Tuple t = list.get(index[0]++);
    QuadTreeNode node = new QuadTreeNode(t.val);
    for (int i = 0; i < 4; I++) {
       if ((t.state & (1 << i)) > 0) node.children[i] = deserHelper(list, index);
    }
    return node;
  }
}
class Tuple {
  int val;
  int state;
  public Tuple(int val) {
     this.val = val;
     this.state = 0;
  }
  public String toString() {
    return t.val + "," + t.state;
  }
  public Tuple toTuple(String str) {
     if (str == null || str.length() == 0) return null;
     String[] vals = str.split(',');
     Tuple t = new Tuple(Integer.parseInt(vals[0]));
     t.state = Integer.parseInt(vals[1]);
    return t;
  }
}

 

                            
                        
                    
                    
                    

你可能感兴趣的:(QuadTree Serialization/Deserialization)