// Encodes a tree to a single string. public String serialize(TreeNode root){ if (root == null) { return""; } // 定义一个队列保存每层节点 LinkedList<TreeNode> deque = new LinkedList<>(); // 用一个list接收结果,最后转为string StringBuilder result = new StringBuilder(); deque.add(root); boolean append = true; // 循环遍历 while (!deque.isEmpty()) { TreeNode cur = deque.pop(); if (cur == null) { result.append("null,"); append = false; continue; } result.append(cur.val).append(","); deque.add(cur.left); deque.add(cur.right); }
// Decodes your encoded data to tree. public TreeNode deserialize(String data){ if (data.length() == 0) { returnnull; } String[] rootArr = data.split(","); int size = rootArr.length; for (int i = size - 1; i >= 0; i--) { if (!"null".equals(rootArr[i])) { size--; } else { break; } }
int index = 0; TreeNode root = new TreeNode(Integer.parseInt(rootArr[0])); index++; LinkedList<TreeNode> deque = new LinkedList<>(); deque.add(root);
while (index < size) { TreeNode cur = deque.pop(); if (!"null".equals(rootArr[index])) { TreeNode rootLeft = new TreeNode(Integer.parseInt(rootArr[index])); cur.left = rootLeft; deque.add(rootLeft); } index++; if (!"null".equals(rootArr[index])) { TreeNode rootRight = new TreeNode(Integer.parseInt(rootArr[index])); cur.right = rootRight; deque.add(rootRight); } index++; }