Serialize and Deserialize Binary Tree

Serialize and Deserialize Binary Tree


首先,很抱歉,停更了幾天。因?yàn)樯×?,燒到?9度,喉嚨疼的要命,不知道是不是跟北京最近的霧霾天氣有關(guān)?,F(xiàn)在好一些了,從今天起恢復(fù)更新。

今天是一道有關(guān)二叉樹的題目,來自LeetCode,難度為Medium,Acceptance為24.6%。

題目如下


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.

解題思路及代碼見閱讀原文

回復(fù)0000查看更多題目

解題思路


首先,老規(guī)矩,看到二叉樹,想到二叉樹的三種遍歷方式。

然后,這里需要序列化和反序列化二叉樹,可以采用的方法很多了。多種遍歷方式都可以,只有在序列化和反序列化時(shí)采用相同的遍歷方式即可。其中較為簡單的是前序遍歷層次遍歷

因?yàn)椴捎?strong>層次遍歷行需要利用隊(duì)列,會(huì)多引入一種數(shù)據(jù)結(jié)構(gòu),所以這里采用前序遍歷,這種方法也比較容易理解和實(shí)現(xiàn)。

  • 序列化,即將二叉樹轉(zhuǎn)成字符串。因?yàn)槎鏄渲邪?code>null節(jié)點(diǎn)。需要采用一個(gè)特殊字符標(biāo)記,因?yàn)檫@里的二叉樹的值都是數(shù)字,所以可以采用非數(shù)字作為標(biāo)記,如采用X。每個(gè)節(jié)點(diǎn)間用,分割。然后就是按照前序遍歷的方法,輸入二叉樹成字符串,較為簡單,不再贅述。

  • 反序列化,即將剛才生成的字符串轉(zhuǎn)換成二叉樹。首先,將字符串按照,split成字符串數(shù)組的形式,該數(shù)組中每一個(gè)元素即為一個(gè)二叉樹的節(jié)點(diǎn)。
    這里本來可以很簡單的用一個(gè)全局變量記錄,當(dāng)前遍歷的數(shù)組index,但是因?yàn)轭}目中要求采用stateless的方式,所以必須換種方式。
    可以采用List的方式,將已經(jīng)遍歷的節(jié)點(diǎn)刪除,剩下的就是當(dāng)該字符串不是X時(shí),按照前序遍歷的方式重建二叉樹。

代碼如下


Java版

public class Codec {
    private static final String spliter = ",";
    private static final String NN = "X";

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        buildString(root, sb);
        return sb.toString();
    }

    private void buildString(TreeNode node, StringBuilder sb) {
        if (node == null) {
            sb.append(NN).append(spliter);
        } else {
            sb.append(node.val).append(spliter);
            buildString(node.left, sb);
            buildString(node.right,sb);
        }
    }
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        Deque<String> nodes = new LinkedList<>();
        nodes.addAll(Arrays.asList(data.split(spliter)));
        return buildTree(nodes);
    }

    private TreeNode buildTree(Deque<String> nodes) {
        String val = nodes.remove();
        if (val.equals(NN)) return null;
        else {
            TreeNode node = new TreeNode(Integer.valueOf(val));
            node.left = buildTree(nodes);
            node.right = buildTree(nodes);
            return node;
        }
    }
}

關(guān)注我
該公眾號會(huì)每天推送常見面試題,包括解題思路是代碼,希望對找工作的同學(xué)有所幫助

image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容