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

  1. 二叉樹的序列化與反序列化
/**
 * 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 serialize1(TreeNode root) {
        //#表示空結點 !結點間的分隔符
        if(root == null){
            return "#!";
        }
        String str = root.val + "!";
        str += serialize(root.left);
        str += serialize(root.right);
        return str;
    }

    //解法2 使用StringBuilder 比str+ 的形式運行效率高
    public String serialize(TreeNode root) {
        StringBuilder res = ser_help(root,new StringBuilder());
        return res.toString();
    }
    public StringBuilder ser_help(TreeNode root,StringBuilder str){
        if(root == null){
            str.append("#!");
            return str;
        }
        str.append(root.val);
        str.append("!");
        str = ser_help(root.left,str);
        str = ser_help(root.right,str);
        return str;
    }

    // Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
        String []arr=data.split("!");
        Queue <String> queue=new LinkedList<String>();
        for(int i=0;i<arr.length;i++){
            queue.offer(arr[i]);
        }
        //調用先序遍歷遞歸方法(改動後)依次重建二叉樹
        return deserialize(queue);
    }
    //傳入隊列
    public TreeNode deserialize(Queue <String> queue){
        //依次彈出隊列中的節點值
        String str=queue.poll();
        //如果是"#",代表節點值爲空,返回null
        if(str.equals("#")){
            return null;  
        }
        //若節點值不爲空,將其由String轉換回int
        //將其作爲當前節點值新建當前節點
        TreeNode root=new TreeNode(Integer.parseInt(str));
        //遞歸調用連接當前節點的左右節點
        root.left=deserialize(queue);
        root.right=deserialize(queue);
        //遞歸完成後返回當前節點
        return root;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章