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));
    
  • 相关阅读:
    solr初步了解
    jieba初步了解
    情感计算emokit
    常用命令
    java跨域访问问题记录
    mysql 免安装版配置
    Android 图片缩放方法
    spring android http
    sql join 与where的区别
    android activitygroup 使用
  • 原文地址:https://www.cnblogs.com/magicya/p/10626861.html
Copyright © 2011-2022 走看看