|
| 1 | +package hard; |
| 2 | + |
| 3 | +import classes.TreeNode; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +/** |
| 7 | + * Created by fishercoder1534 on 9/30/16. |
| 8 | + */ |
| 9 | +public class SerializeandDeserializeBinaryTree { |
| 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 | + public String serialize(TreeNode root) { |
| 21 | + if(root == null) return ""; |
| 22 | + |
| 23 | + StringBuilder sb = new StringBuilder(); |
| 24 | + Queue<TreeNode> queue = new LinkedList(); |
| 25 | + queue.offer(root); |
| 26 | + while(!queue.isEmpty()){ |
| 27 | + int size = queue.size(); |
| 28 | + for(int i = 0; i < size; i++){ |
| 29 | + TreeNode curr = 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 | + return sb.toString(); |
| 41 | + } |
| 42 | + |
| 43 | + // Decodes your encoded data to tree. |
| 44 | + public TreeNode deserialize(String data) { |
| 45 | + if(data == null || data.isEmpty()) return null; |
| 46 | + |
| 47 | + String[] nodes = data.split(" "); |
| 48 | + TreeNode root = new TreeNode(Integer.valueOf(nodes[0])); |
| 49 | + Queue<TreeNode> queue = new LinkedList(); |
| 50 | + queue.offer(root); |
| 51 | + for(int i = 1; i < nodes.length; i++){ |
| 52 | + TreeNode curr = queue.poll(); |
| 53 | + if(!nodes[i].equals("#")){ |
| 54 | + curr.left = new TreeNode(Integer.valueOf(nodes[i])); |
| 55 | + queue.offer(curr.left); |
| 56 | + } |
| 57 | + if(!nodes[++i].equals("#")){ |
| 58 | + curr.right = new TreeNode(Integer.valueOf(nodes[i])); |
| 59 | + queue.offer(curr.right); |
| 60 | + } |
| 61 | + } |
| 62 | + return root; |
| 63 | + } |
| 64 | + |
| 65 | + |
| 66 | + public static void main(String...args){ |
| 67 | + |
| 68 | + } |
| 69 | +} |
0 commit comments