LeetCode 499 二叉樹的序列化和反序列化 java

一、題目

分析:

用一定方式記錄二叉樹成字符串,然後再將字符串解析成二叉樹 

無所謂遍歷順序,先序、中序、後續都可以,甚至按層遍歷也是可以的,只要前後規則一致就是可以的

然後我是採用左神的方法,節點之間使用_佔位符,空指針用#表示,否則不是很難知道左右子樹什麼時候終止,左神機智

一個小例子

 

比如這個,按照先序遍歷序列化結果爲:0_1_3_#_#_#_2_#_4_#_#

然後反序列化的時候,根據佔位符和表示空的符號就可以生成一棵二叉樹

二、代碼實現(java) 

知識點:

看API:

add():Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never throw IllegalStateException or return false.

offer():Inserts the specified element at the tail of this queue. As the queue is unbounded, this method will never return false.

 

區別:兩者都是往隊列尾部插入元素,不同的時候,當超出隊列界限的時候,add()方法是拋出異常讓你處理,而offer()方法是直接返回false

實現

/**
 * 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) {
        if(root==null){
            return "#_";
        }
        String res = root.val + "_";
        res += serialize(root.left);
        res += serialize(root.right);
        return res;
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String []values = data.split("_");
        Queue<String> queue = new LinkedList<String>();
        for(int i = 0; i!=values.length; i++){
            queue.offer(values[i]);
        }
        return reconPreOrder(queue);
    }
    public TreeNode reconPreOrder(Queue<String> queue){
        String value = queue.poll();
        if(value.equals("#")){
            return null;
        }
        TreeNode root = new TreeNode(Integer.valueOf(value));
        root.left = reconPreOrder(queue);
        root.right = reconPreOrder(queue);
        return root;
    }
}

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

 

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