zoukankan      html  css  js  c++  java
  • leetcode297- Serialize and Deserialize Binary Tree- hard

    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.

    用BFS做,用ArrayList存储中间的状态,tree-list-string, string-list-tree。这样写可以比较清楚。

    细节:1.老话equals,每个地方都检查!2.sb.deleteCharAt(), sb.delete(idx1, idx2),这两个可以,没有remove. 3.deserialize的时候用arrayList+int idx追踪被添加结点比较好,比用queue好写。4.deserialize的时候要先把root提早拉出来,没办法 5.deserialize的时候要用到string.split(",")方法。

    1.自己写的,queue

    /**
     * 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) {
            StringBuilder sb = new StringBuilder();
            Queue<TreeNode> q = new LinkedList<>();
            q.offer(root);
            while (!q.isEmpty()) {
                int size = q.size();
                for (int i = 0; i < size; i++) {
                    TreeNode n = q.poll();
                    if (n == null) {
                        sb.append('#').append(',');
                        continue;
                    }
                    sb.append(n.val).append(',');
                    q.offer(n.left);
                    q.offer(n.right);
                }
            }
            // 注意API sb.delete(idx1, idx2); sb.deleteCharAt(idx),不是remove
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if (data.equals("#")) {
                return null;
            }
            String[] vals = data.split(",");
            TreeNode crt = new TreeNode(Integer.parseInt(vals[0]));
            TreeNode root = crt;
            boolean isLeft = true;
            Queue<TreeNode> q = new LinkedList<>();
            for (int i = 1; i < vals.length; i++) {
                TreeNode item = null;
                // 又写错成用!=对比了!!千万小心啊
                if (!vals[i].equals("#")) {
                    item = new TreeNode(Integer.parseInt(vals[i]));
                    q.offer(item);
                }
                if (isLeft) {
                    crt.left = item;
                } else {
                    crt.right = item;
                    crt = q.poll();
                }
                isLeft = !isLeft;
            }
            return root;
        }
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.deserialize(codec.serialize(root));

    2.九章的,list

    /**
    * 本参考程序来自九章算法,由 @九章算法 提供。版权所有,转发请注明出处。
    * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
    * - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,
    * - Big Data 项目实战班,算法面试高频题班, 动态规划专题班
    * - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code
    */ 
    
    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */
    class Solution {
        /**
         * This method will be invoked first, you should design your own algorithm 
         * to serialize a binary tree which denote by a root node to a string which
         * can be easily deserialized by your own "deserialize" method later.
         */
        public String serialize(TreeNode root) {
            if (root == null) {
                return "{}";
            }
    
            ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
            queue.add(root);
    
            for (int i = 0; i < queue.size(); i++) {
                TreeNode node = queue.get(i);
                if (node == null) {
                    continue;
                }
                queue.add(node.left);
                queue.add(node.right);
            }
    
            while (queue.get(queue.size() - 1) == null) {
                queue.remove(queue.size() - 1);
            }
    
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            sb.append(queue.get(0).val);
            for (int i = 1; i < queue.size(); i++) {
                if (queue.get(i) == null) {
                    sb.append(",#");
                } else {
                    sb.append(",");
                    sb.append(queue.get(i).val);
                }
            }
            sb.append("}");
            return sb.toString();
        }
        
        /**
         * This method will be invoked second, the argument data is what exactly
         * you serialized at method "serialize", that means the data is not given by
         * system, it's given by your own serialize method. So the format of data is
         * designed by yourself, and deserialize it here as you serialize it in 
         * "serialize" method.
         */
        public TreeNode deserialize(String data) {
            if (data.equals("{}")) {
                return null;
            }
            String[] vals = data.substring(1, data.length() - 1).split(",");
            ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
            TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
            queue.add(root);
            int index = 0;
            boolean isLeftChild = true;
            for (int i = 1; i < vals.length; i++) {
                if (!vals[i].equals("#")) {
                    TreeNode node = new TreeNode(Integer.parseInt(vals[i]));
                    if (isLeftChild) {
                        queue.get(index).left = node;
                    } else {
                        queue.get(index).right = node;
                    }
                    queue.add(node);
                }
                if (!isLeftChild) {
                    index++;
                }
                isLeftChild = !isLeftChild;
            }
            return root;
        }
    }
  • 相关阅读:
    oracle12c中新能优化新特性之热度图和自动数据优化
    Oracle10g以上sysaux表空间的维护和清理
    mysql 及 posgresql之优劣势大比拼
    Oracle外部表的管理和应用
    Oracle ASM 相关的 视图(V$) 和 数据字典(X$)
    Oracle12c功能增强新特性之维护&amp;升级&amp;恢复&amp;数据泵等
    Oracle12c功能增强 新特性之管理功能的增强
    Oracle12c 中RAC功能增强新特性之ASM&amp;Grid
    oracle12c新特点之可插拔数据库(Pluggable Database,PDB)
    SRM-697-DIV2
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7907086.html
Copyright © 2011-2022 走看看