// Encodes a tree to a single string. public String serialize(TreeNode root) { if(root == null) return "[]"; Deque<TreeNode> deque = new LinkedList<>(); deque.addLast(root); StringBuilder sb = new StringBuilder(); sb.append("["); while (!deque.isEmpty()){ TreeNode node = deque.pollFirst(); if(node!=null) { sb.append(node.val); sb.append(","); deque.addLast(node.left); deque.addLast(node.right); }else{ sb.append("null,"); } } sb.deleteCharAt(sb.length()-1); //删除结尾的逗号 //将结尾的null删除 while (sb.lastIndexOf("null")==sb.length()-4){ sb.delete(sb.length()-5,sb.length()); } sb.append("]"); return sb.toString(); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if(data.equals("[]")) return null; data = data.substring(1,data.length()-1); String[] datas = data.split(","); ArrayList<TreeNode> list = new ArrayList<>(); for (String s : datas) { //将字符串转换为整数 if (s.equals("null")) { list.add(null); } else { int x = Integer.parseInt(s); list.add(new TreeNode(x)); } } int len = list.size(); TreeNode head = list.get(0); if(len == 1) return head; int i = 0,j = 1; while (j<len){ if(list.get(i) == null) { i++; continue; } list.get(i).left = list.get(j); if(j+1<len){ list.get(i).right = list.get(j+1); } j+=2; i++; } return head; }
这道题感觉算不上是难题