|
| 1 | +packagehard; |
| 2 | + |
| 3 | +importclasses.TreeNode; |
| 4 | +importjava.util.*; |
| 5 | + |
| 6 | +/** |
| 7 | + * Created by fishercoder1534 on 9/30/16. |
| 8 | + */ |
| 9 | +publicclassSerializeandDeserializeBinaryTree { |
| 10 | + |
| 11 | +/**The idea is very straightforward: |
| 12 | + use "#" as the terminator, do BFS, level order traversal to store all nodes values into a StringBuilder. |
| 13 | +
|
| 14 | + When deserializing, also, use a queue: pop the root into the queue first, then use a for loop to construct each node, |
| 15 | + then eventually just return the root. |
| 16 | + */ |
| 17 | + |
| 18 | + |
| 19 | +// Encodes a tree to a single string. |
| 20 | +publicStringserialize(TreeNoderoot) { |
| 21 | +if(root ==null)return""; |
| 22 | + |
| 23 | +StringBuildersb =newStringBuilder(); |
| 24 | +Queue<TreeNode>queue =newLinkedList(); |
| 25 | +queue.offer(root); |
| 26 | +while(!queue.isEmpty()){ |
| 27 | +intsize =queue.size(); |
| 28 | +for(inti =0;i <size;i++){ |
| 29 | +TreeNodecurr =queue.poll(); |
| 30 | +if(curr ==null){ |
| 31 | +sb.append("# "); |
| 32 | +continue; |
| 33 | + } |
| 34 | +sb.append(curr.val); |
| 35 | +sb.append(" "); |
| 36 | +queue.offer(curr.left); |
| 37 | +queue.offer(curr.right); |
| 38 | + } |
| 39 | + } |
| 40 | +returnsb.toString(); |
| 41 | + } |
| 42 | + |
| 43 | +// Decodes your encoded data to tree. |
| 44 | +publicTreeNodedeserialize(Stringdata) { |
| 45 | +if(data ==null ||data.isEmpty())returnnull; |
| 46 | + |
| 47 | +String[]nodes =data.split(" "); |
| 48 | +TreeNoderoot =newTreeNode(Integer.valueOf(nodes[0])); |
| 49 | +Queue<TreeNode>queue =newLinkedList(); |
| 50 | +queue.offer(root); |
| 51 | +for(inti =1;i <nodes.length;i++){ |
| 52 | +TreeNodecurr =queue.poll(); |
| 53 | +if(!nodes[i].equals("#")){ |
| 54 | +curr.left =newTreeNode(Integer.valueOf(nodes[i])); |
| 55 | +queue.offer(curr.left); |
| 56 | + } |
| 57 | +if(!nodes[++i].equals("#")){ |
| 58 | +curr.right =newTreeNode(Integer.valueOf(nodes[i])); |
| 59 | +queue.offer(curr.right); |
| 60 | + } |
| 61 | + } |
| 62 | +returnroot; |
| 63 | + } |
| 64 | + |
| 65 | + |
| 66 | +publicstaticvoidmain(String...args){ |
| 67 | + |
| 68 | + } |
| 69 | +} |