1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
public class Codec {
private static final String EMPTY = "null";
public String serialize(TreeNode root) { if (root == null) return ""; StringBuilder builder = new StringBuilder(); Deque<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode cur = queue.poll(); if (cur == null) { builder.append(EMPTY).append(","); } else { builder.append(cur.val).append(","); queue.offer(cur.left); queue.offer(cur.right); } } return builder.toString(); }
public TreeNode deserialize(String data) { if (data.equals("")) return null; String[] split = data.split(","); Deque<String> nodes = new LinkedList<>(List.of(split)); TreeNode root = new TreeNode(Integer.parseInt(nodes.poll())); Deque<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode cur = queue.poll(); String left = nodes.poll(); String right = nodes.poll(); if (!left.equals(EMPTY)) { cur.left = new TreeNode(Integer.parseInt(left)); queue.offer(cur.left); } if (!right.equals(EMPTY)) { cur.right = new TreeNode(Integer.parseInt(right)); queue.offer(cur.right); } } return root; } }
|