leetcode297. 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.

設計一個方法將一個二叉樹序列化並反序列化。序列化是指將對象轉化成一個字符串,該字符串能夠在網絡上傳輸,而且到達目的地後能夠經過反序列化恢復成原來的對象。node

在Leetcode中,樹的序列化是經過廣度優先遍歷實現的,就如題目中所介紹的那樣。面試

這裏咱們使用中序遍從來解決這個問題。微信

思路和代碼

中序遍歷是指遞歸的先遍歷當前節點,而後按一樣的方式遞歸的遍歷左子樹,再遞歸的遍歷右子樹。所以題目中的例子的中序遍歷結果爲[1,2,3,4,5]。可是,標準的中序遍歷並不能使咱們將該結果反構形成一棵樹,咱們丟失了父節點和子節點之間的關係。所以咱們須要適當的插入空值來保存父節點和子節點的關係。網絡

所以,咱們將訪問到空值也記錄下來,結果以下[1,2, , ,3,4, , ,5, , ]app

這裏咱們也能夠明顯的看出來,中序遍歷須要保存的空值遠遠多於廣度優先遍歷。less

那麼咱們如何將這個字符串反序列化呢?
其實思路仍是同樣的,將其根據分隔符分割後傳入隊列,不斷從隊列頭讀取數據,先構建當前節點,而後依次構建左子樹和右子樹,若是遇到空值,則返回遞歸。ui

代碼以下:this

private static final String NULL = "N";
    private static final String SPLITOR = ",";
    
     // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder result = new StringBuilder();
        inOrder(root, result);
        return result.toString();
    }
    
    private void inOrder(TreeNode root, StringBuilder result){
        if(root==null){
            result.append(NULL).append(SPLITOR);
        }else{
            result.append(root.val).append(SPLITOR);
            inOrder(root.left, result);
            inOrder(root.right, result);
        }
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        Deque<String> nodes = new LinkedList<String>(Arrays.asList(data.split(SPLITOR)));
        return buildTree(nodes);
    }
    
    private TreeNode buildTree(Deque<String> nodes) {
        String val = nodes.remove();
        if (val.equals(NULL)) return null;
        else {
            TreeNode node = new TreeNode(Integer.valueOf(val));
            node.left = buildTree(nodes);
            node.right = buildTree(nodes);
            return node;
        }
    }

clipboard.png
想要了解更多開發技術,面試教程以及互聯網公司內推,歡迎關注個人微信公衆號!將會不按期的發放福利哦~spa

相關文章
相關標籤/搜索