publicclassCodec{// Encodes a tree to a single string.publicStringserialize(TreeNode root){if(root ==null)return"null";String left =serialize(root.left);String right =serialize(root.right);return root.val +","+ left +","+ right;}// Decodes your encoded data to tree.publicTreeNodedeserialize(String data){Deque<String> dq =newArrayDeque<>(Arrays.asList(data.split(",")));returndeserialize(dq);}TreeNodedeserialize(Deque<String> dq){String cur = dq.poll();if(cur.equals("null"))returnnull;TreeNode root =newTreeNode(Integer.valueOf(cur));
root.left =deserialize(dq);
root.right =deserialize(dq);return root;}}
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
层序遍历
publicclassCodec{// Encodes a tree to a single string.publicStringserialize(TreeNode root){if(root ==null)return"null";StringBuilder sb =newStringBuilder();Deque<TreeNode> queue =newLinkedList<>();
queue.offer(root);while(!queue.isEmpty()){TreeNode cur = queue.poll();if(cur ==null){
sb.append("null,");continue;}
sb.append(cur.val +",");
queue.offer(cur.left);
queue.offer(cur.right);}return sb.toString();}// Decodes your encoded data to tree.publicTreeNodedeserialize(String data){if(data.equals("null"))returnnull;Deque<String> q1 =newArrayDeque<>(Arrays.asList(data.split(",")));TreeNode root =newTreeNode(Integer.valueOf(q1.poll()));Deque<TreeNode> q2 =newArrayDeque<>();
q2.offer(root);while(!q1.isEmpty()){TreeNode cur = q2.poll();String left = q1.poll();String right = q1.poll();if(!left.equals("null")){
cur.left =newTreeNode(Integer.valueOf(left));
q2.offer(cur.left);}if(!right.equals("null")){
cur.right =newTreeNode(Integer.valueOf(right));
q2.offer(cur.right);}}return root;}}