算法-二叉樹-序列化與反序列化

算法-二叉樹-序列化與反序列化

1 搜索插入位置

1.1 題目出處

https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree

1.2 題目描述

序列化是將一個數據結構或者對象轉換爲連續的比特位的操作,進而可以將轉換後的數據存儲在一個文件或者內存中,同時也可以通過網絡傳輸到另一個計算機環境,採取相反方式重構得到原數據。

請設計一個算法來實現二叉樹的序列化與反序列化。這裏不限定你的序列 / 反序列化算法執行邏輯,你只需要保證一個二叉樹可以被序列化爲一個字符串並且將這個字符串反序列化爲原始的樹結構。

示例:

你可以將以下二叉樹:

   1
  / \
 2   3
    / \
   4   5

序列化爲 “[1,2,3,null,null,4,5]”
提示: 這與 LeetCode 目前使用的方式一致,詳情請參閱 LeetCode 序列化二叉樹的格式。你並非必須採取這種方式,你也可以採用其他的方法解決這個問題。

說明: 不要使用類的成員 / 全局 / 靜態變量來存儲狀態,你的序列化和反序列化算法應該是無狀態的。

2 BFS

2.1 思路

序列化時使用隊列以BFS順序遍歷樹。

反序列化時同樣採用隊列BFS,並輔以i+1和i+2作爲左右子樹。

2.2 代碼

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode t = queue.poll();
            if(t == null){
                sb.append("null").append(",");
                continue;
            }
            sb.append(t.val).append(",");
            queue.add(t.left);
            queue.add(t.right);
        }
        return sb.substring(0, sb.length()-1);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        TreeNode root = null;
        String[] datas = data.split(",");
        root = datas[0].equals("null") ? null : new TreeNode(Integer.parseInt(datas[0]));
        if(root == null){
            return root;
        }
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int i = 1;
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if(!datas[i].equals("null")){
                TreeNode left = new TreeNode(Integer.parseInt(datas[i]));
                cur.left = left;
                queue.add(left);
            }
            i++;
            if(!datas[i].equals("null")){
                TreeNode right = new TreeNode(Integer.parseInt(datas[i]));
                cur.right = right;
                queue.add(right);
            }
            i++;
        }
        return root;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

2.3 時間複雜度

在這裏插入圖片描述
O(N)

2.4 空間複雜度

O(N)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章