zoukankan      html  css  js  c++  java
  • leetcode297. 二叉树的序列化与反序列化

    代码

    /**
     * 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 preStr) {
            String[] values = preStr.split("!");
            Queue<String> queue = new LinkedList<>();
            for(int i = 0; i != values.length; i++){
                queue.offer(values[i]);
            }
            return deserialize(queue);
        }
        private TreeNode deserialize(Queue<String> queue){
            String value = queue.poll();
            if(value.equals("#")){
                return null;
            }
            TreeNode node = new TreeNode(Integer.valueOf(value));
            node.left = deserialize(queue);
            node.right = deserialize(queue);
            return node;
        }
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec = new Codec();
    // codec.deserialize(codec.serialize(root));
    
  • 相关阅读:
    磁盘映射命令
    CentOS 配置XWIN/VNC
    生成一个随机数,让用户输入猜这个数字,有三次机会
    自己练习读取写入txt
    python学习笔记:文件操作和集合(转)
    接口测试基础
    nginx_tomcat负载均衡环境
    mysql索引
    shell脚本
    linux基础知识(四)
  • 原文地址:https://www.cnblogs.com/magicya/p/10626861.html
Copyright © 2011-2022 走看看