zoukankan      html  css  js  c++  java
  • 297. 二叉树的序列化与反序列化 (JAVA)

    序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。

    请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。

    提示: 输入输出格式与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。

    示例 1:


    输入:root = [1,2,3,null,null,4,5]
    输出:[1,2,3,null,null,4,5]
    示例 2:

    输入:root = []
    输出:[]
    示例 3:

    输入:root = [1]
    输出:[1]
    示例 4:

    输入:root = [1,2]
    输出:[1,2]

    思路:用前序遍历序列化,然后根据有null节点的前序遍历构建进行反序列化。

    /**
     * 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) {
            TreeNode current;
            String result = "";
            Stack<TreeNode> stack = new Stack<>();
            if(root != null) {
                stack.push(root);
            }
            while(!stack.empty()) {
                current = stack.peek();
                stack.pop();
                if(current != null) {
                    stack.push(current.right);
                    stack.push(current.left);
                    result += current.val + ",";
                } else {
                    result += "#,";
                }
            }
            return result;
        }
    
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if(data == null || data.length() == 0) return null;
    
            values = data.split(",");
            depth = 0;
            return deserializeDFS();
        }
    
        private TreeNode deserializeDFS() {
            if(values[depth].equals("#")) {
                depth++;
                return null;
            }
    
            TreeNode root = new TreeNode(Integer.parseInt(values[depth]));
            depth++;
            root.left = deserializeDFS();
            root.right = deserializeDFS();
    
            return root;
        }
    
        private String[] values;
        private int depth;
    
    }
    
    // Your Codec object will be instantiated and called as such:
    // Codec ser = new Codec();
    // Codec deser = new Codec();
    // TreeNode ans = deser.deserialize(ser.serialize(root));
  • 相关阅读:
    爬虫技术浅析 | WooYun知识库
    爬虫技术实战 | WooYun知识库
    爬虫技术实战 | WooYun知识库
    Day 16: Goose Extractor —— 好用的文章提取工具
    mysql中间件研究(Atlas,cobar,TDDL)
    cygwin with openssh
    win2008 ent r2 开启端口
    MobaSSH SSH server for Windows
    自动化运维工具Ansible详细部署
    中科院NLPIR中文分词java版
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/14683326.html
Copyright © 2011-2022 走看看