【LeetCode 】: 297. 二叉樹的序列化與反序列化

297. 二叉樹的序列化與反序列化

問題描述:

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

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

題目鏈接:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/

示例1

你可以將以下二叉樹:
1
/
2 3
/
4 5
序列化爲 “[1,2,3,null,null,4,5]”

思路:

序列化非常簡單,直接使用層次遍歷算法,拼湊出結果字符串,只需主意,在序列化最後,刪除最後一個多餘的逗號。本題的難點在於下面反序列化的過程。

同樣利用隊列,對字符串進行反序列化,首先去除[]符號,把元素提取出來。隨後初始化隊列,用一個下標index標記當前掃描到字符串的哪個部位。把字符串的第一個節點入隊。然後判斷循環,如果隊列不空,令隊頭出隊,然後把出隊節點的左節點和右節點分別賦值爲字符串的前兩個元素。這樣就實現了對一個節點左孩子和右孩子的提取。之後,如果左孩子不爲空,把左孩子入隊,如果右孩子不爲空,把右孩子入隊。即可實現反序列化。

完整代碼:

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root == null)
            return "[]";
        StringBuffer res = new StringBuffer("[");
        Queue<TreeNode> queue = new LinkedList();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode tmp = queue.poll();
            if(tmp != null) {
                res.append(tmp.val + ",");
                queue.add(tmp.left);
                queue.add(tmp.right);
            }else {
                res.append("null,");
            }
        }
        return res.substring(0 , res.length() - 1) + "]";
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data == null && data.equals("[]"))
            return null;
        String res = data.substring(1 , data.length() - 1);
        String values[] = res.split(",");
        int index = 0;
        TreeNode node = getTreeNode(values[index++]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(node);
        while (!queue.isEmpty()) {
            TreeNode tmp = queue.poll();
            tmp.left = getTreeNode(values[index++]);
            tmp.right = getTreeNode(values[index++]);
            if (tmp.left != null) {
                queue.add(tmp.left);
            }
            if (tmp.right != null)
                queue.add(tmp.right);

        }
        return node;
    }

    public TreeNode getTreeNode(String s) {
        if(s.equals("null"))
            return null;
        return new TreeNode(Integer.valueOf(s));

    }

附加GitHub鏈接

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