Serialize and Deserialize Binary Tree

题目:

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.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

分析:利用层次遍历进行序列化,在反序列化时,TreeNode数组中每个节点的left节点下标为2*(i-nullNum)+1,right节点下标为2*(i-nullNum)+2,其中nullNum为TreeNode数组中元素null的个数。

Java代码及注释如下:

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {      // 1,2,3,null,null,4,5,null,null,null,null
        if (root == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (! queue.isEmpty()) {       //利用队列进行层次遍历(广搜)
            TreeNode tmp = queue.poll();
            if (tmp != null) {
                sb.append(tmp.val);
                queue.offer(tmp.left);
                queue.offer(tmp.right);
            } else {
                sb.append("null");
            }
            sb.append(",");
        }
        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }         

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if ("".equals(data)) {
            return null;
        }
        String[] tmp = data.split(",");
        TreeNode[] node = new TreeNode[tmp.length]; // 根据序列化数组元素构造TreeNode数组.
        for (int i = 0; i < node.length; i++) {
            if ("null".equals(tmp[i])) {
                node[i] = null;
            } else {
                node[i] = new TreeNode(Integer.parseInt(tmp[i]));
            }
        }
        int nullNum = 0;
        for (int i = 0; i < tmp.length; i++) { //找到TreeNode数组中每个node所指向的left和right节点。
            if (node[i] != null) {
                node[i].left = node[2*(i-nullNum)+1];
                node[i].right = node[2*(i-nullNum)+2];
            } else {
                nullNum++;
            }
        }
        return node[0]; //返回root
    }
时间: 2024-10-17 07:24:14

Serialize and Deserialize Binary Tree的相关文章

[LeetCode][JavaScript]Serialize and Deserialize Binary Tree

Serialize and Deserialize Binary Tree 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 reconstruct

297. Serialize and Deserialize Binary Tree

297. Serialize and Deserialize Binary Tree Total Accepted: 47713 Total Submissions: 149430 Difficulty: Hard Contributors: Admin Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in

[Lintcode]7. Serialize and Deserialize Binary Tree/[Leetcode]297. Serialize and Deserialize Binary Tree

7. Serialize and Deserialize Binary Tree/297. Serialize and Deserialize Binary Tree 本题难度: Medium/Hard Topic: Binary Tree Description Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called '

【LeetCode】297. Serialize and Deserialize Binary Tree

二叉树的序列化与反序列化. 如果使用string作为媒介来存储,传递序列化结果的话,会给反序列话带来很多不方便. 这里学会了使用 sstream 中的 输入流'istringstream' 和 输出流'ostringstream'. istringstream in; in >> str; 这里没执行一次就会倒出一个string (因为in流中使用了' '空格 作为分割符, 所以可以分成很多个string) 建树的时候使用先序建立二叉树. 关键代码如下: TreeNode* build(ist

Leetcode: Serialize and Deserialize Binary Tree

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 comput

LeetCode 297: Serialize and Deserialize Binary Tree

1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Codec { 11 12 // Encodes a tree to a single string. 13 public Str

【树】Serialize and Deserialize Binary Tree

题目: 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 co

LeetCode——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 a

难1 297. Serialize and Deserialize Binary Tree

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 compute