lintcode 中等题:binary tree serialization 二叉树的序列化和反序列化

题目

二叉树的序列化和反序列化

设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。

如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。

样例

给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7},表示如下的树结构:

  3
 / 9  20
  /   15   7

我们的数据是进行BFS遍历得到的。当你测试结果wrong answer时,你可以作为输入调试你的代码。

你可以采用其他的方法进行序列化和反序列化。

解题

参考九章程序

看看注释就理解了,但是我表示自己想不出来Java

/**
 * 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) {
        // write your code here
        if( root == null)
            return "{}";
        ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
        queue.add(root);
        // 将二叉树的个节点按照从上到下、从左到有的存储在queue中
        for(int i=0;i<queue.size();i++){
            TreeNode q = queue.get(i);
            if(q== null)
                continue;
            queue.add(q.left);
            queue.add(q.right);
        }
        // 去除叶子节点的左右孩子,这个孩子是空值
        while(queue.get(queue.size() - 1) == null){
            queue.remove(queue.size() - 1);
        }
        // 遍历queue把转换成字符串
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append(queue.get(0).val);
        for(int i=1;i<queue.size(); i++){
            TreeNode q = queue.get(i);
            if(q!= null){
                sb.append(",");
                sb.append(q.val);
            }else{
                sb.append(",#");
            }
        }
        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) {
        // write your code here
        if(data == "{}")
            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;
    }
}
时间: 2024-08-12 09:39:11

lintcode 中等题:binary tree serialization 二叉树的序列化和反序列化的相关文章

[LintCode] Invert Binary Tree 翻转二叉树

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. Example Given 4 points: (1,2), (3,6), (0,0), (1,3). The maximum number is 3. LeeCode上的原题,可参见我之前的博客Invert Binary Tree 翻转二叉树. 解法一: // Recursion class So

【LeetCode-面试算法经典-Java实现】【104-Maximum Depth of Binary Tree(二叉树的最大深度)】

[104-Maximum Depth of Binary Tree(二叉树的最大深度)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 题目大意 给定

【LeetCode-面试算法经典-Java实现】【111-Minimum Depth of Binary Tree(二叉树的最小深度)】

[111-Minimum Depth of Binary Tree(二叉树的最小深度)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 题目大意 给定

遍历二叉树 traversing binary tree 线索二叉树 threaded binary tree 线索链表 线索化

遍历二叉树   traversing binary tree 线索二叉树 threaded binary tree 线索链表 线索化 二叉树3个基本单元组成:根节点.左子树.右子树 以L.D.R分别表示遍历左子树.访问根节点.遍历右子树 可能的情况6种 排列A3 2 LDR LRD DLR DRL RLD RDL 若限定先左后右 LDR LRD  中根序遍历  后根序遍历 DLR  先根序遍历 先/中/后 序遍历 原文地址:https://www.cnblogs.com/yuanjiangw/p

Leetcode 297.二叉树的序列化和反序列化

二叉树地序列化和反序列化 序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据. 请设计一个算法来实现二叉树的序列化与反序列化.这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构. 示例:  你可以将以下二叉树: 序列化为 "[1,2,3,null,null,4,5]" 提示: 这与 Le

二叉树的序列化和反序列化(先序,按层序列化),包含递归图

目录 二叉树的序列化与反序列化 按层序列化 使用#!和!的原因: 二叉树的序列化与反序列化 序列化:将对象的状态信息转换为可以存储或传输的形式的过程 二叉树的序列化:就是将二叉树转换成字符串 二叉树的反序列化:通过字符串还原一棵二叉树,返回树的头节点. 先序序列化二叉树 上面这棵树的先序序列化结果为5!3!2!1!#!#!#!4!#!#!8!7!6!#!#!#!10!9!#!#!11!#!#! 从上图中我们可以看出在节点为空的位置使用"#!"来代替,每个节点后的数值都添加一个"

lintcode 中等题:binary tree level order traversal ii 二叉树的层次遍历II

题目 二叉树的层次遍历 II 给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历) 样例 给出一棵二叉树 {3,9,20,#,#,15,7}, 3 / 9 20 / 15 7 按照从下往上的层次遍历为: [ [15,7], [9,20], [3] ] 解题 和上一题的答案反过来 直接每次在list中第一个位置加入当前层结点 /** * Definition of TreeNode: * public class TreeNode { *

lintcode 中等题:binary tree level order traversal 二叉树的层数遍历

题目 二叉树的层次遍历 给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问) 样例 给一棵二叉树 {3,9,20,#,#,15,7} : 3 / 9 20 / 15 7 返回他的分层遍历结果: [ [3], [9,20], [15,7] ] 挑战 挑战1:只使用一个队列去实现它 挑战2:用DFS算法来做 解题  队列很容易,先加入,然后取出来的同时加入左右孩子节点 在剑指offer中有个题目和这个很类似,其只是层次遍历二叉树,没有要求把每层的节点单独放在一起的. 上面说的规律:每一次打印一

[LeetCode] Verify Preorder Serialization of a Binary Tree 验证二叉树的先序序列化

One way to serialize a binary tree is to use pre-oder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #. _9_ / 3 2 / \ / 4 1 # 6 / \ / \ / # # # # # # For exampl