logologo

后序 序列化与反序列化

Sep 7, 2023

二叉树

序列化

public static Queue<String> posSerial(Node head) {
  Queue<String> ans = new LinkedList<>();
  poss(head, ans);
  return ans;
}
private static void poss(Node head, Queue<String> ans) {
  if (head == null) ans.add("#");
  else {
    poss(head.left, ans);
    poss(head.right, ans);
    ans.add(String.valueOf(head.value));
  }
}

反序列化

public static Node buildByPosQueue(Queue<String> list) {
  if (list == null || list.size() == 0) return null;
  Stack<String> stack = new Stack<>();
  // 将 list(左右中) -> stack(中右左)
  while (!list.isEmpty()) stack.push(list.poll());
  return posb(stack);
}

private static Node posb(Stack<String> s) {
  String value = s.pop();
  if (value == "#") return null;
  Node head = new Node(Integer.valueOf(value));
  head.right = posb(s);
  head.left = posb(s);
  return head;
}

C++Java
浙ICP备2021022773号    2022-PRESENT © ZhengKe