Serialize and Deserialize Binary Tree
题目地址:
https://leetcode.com/problems/serialize-and-deserialize-binary-tree/#/description
题目:
解题思路:
序列化的时候用bfs就好;反序列化的时候也是bfs,但是需要注意的是反序列化的时候每一个node都会对应两个节点,不管是null还是非null,所以存一个boolean的临时变量left,然后每次都flip一下,当queue里面有node并且left是true的时候,就poll出来一个node赋给curr。link: https://discuss.leetcode.com/topic/31264/short-and-straight-forward-bfs-java-code-with-a-queue/6
代码:
https://leetcode.com/problems/serialize-and-deserialize-binary-tree/#/description
题目:
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following tree
1
/ \
2 3
/ \
4 5
as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.解题思路:
序列化的时候用bfs就好;反序列化的时候也是bfs,但是需要注意的是反序列化的时候每一个node都会对应两个节点,不管是null还是非null,所以存一个boolean的临时变量left,然后每次都flip一下,当queue里面有node并且left是true的时候,就poll出来一个node赋给curr。link: https://discuss.leetcode.com/topic/31264/short-and-straight-forward-bfs-java-code-with-a-queue/6
代码:
// Encodes a tree to a single string.public String serialize(TreeNode root) { if(root == null){ return ""; } Queue<TreeNode> queue = new LinkedList<>(); TreeNode curr = root; queue.offer(curr); StringBuilder sb = new StringBuilder(); while(!queue.isEmpty()){ curr = queue.poll(); if(curr == null){ sb.append("n,"); continue; } sb.append(curr.val + ","); queue.offer(curr.left); queue.offer(curr.right); } return sb.toString(); } // Decodes your encoded data to tree.public TreeNode deserialize(String data) { if(data == null || data.length() == 0 ){ return null; } String[] nodes=data.split(","); boolean left=true; if(nodes.length == 0 || nodes[0].equals("n")) { return null; } TreeNode root=new TreeNode(Integer.valueOf(nodes[0])); TreeNode curr=root; Queue<TreeNode> queue = new LinkedList<>(); for(int i = 1; i <= nodes.length - 1; i++){ if(!nodes[i].equals("n")){ TreeNode temp = new TreeNode(Integer.valueOf(nodes[i])); if(left){ curr.left = temp; } else{ curr.right = temp; } queue.offer(temp); } left = !left; if(left && !queue.isEmpty()){ curr = queue.poll(); } } return root; }

Comments
Post a Comment