第二十五题:二叉树的序列化和反序列化(Java)

题目要求:

二叉树的数的序列化和反序列话,二叉树实际是存储在内存中的,一旦断电或者是关机,二叉树的数据就会在内存中丢失。所以我们需要将二叉树的数据保存下来,这个过程叫做持久化或者序列化;将二叉树的数据保存到了磁盘之后,还需要将磁盘中的二叉树的数据加载到内存中去,这过程叫做反序列化。

反序列的标准是:如何序列化的,就怎么反序列话。

代码实现: 

package com.isea.brush.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 二叉树的序列化
 * 解决思路:节点和节点之间使用_ 来分隔,空节点使用#来表示,为什么需要使用#来分隔?
 * 假如所有的节点都是相同的值,且不使用分隔符号,结构不同也会序列化为相同的结果
 */
public class SerialBinaryTree {
    private static class Node {
        private int value;
        private Node left;
        private Node right;

        public Node(int value) {
            this.value = value;
        }
    }

    /**
     * 返回以head为根节点的二叉树的先序序列化后的字符串
     *
     * @param head
     * @return
     */
    public static String serialByPre(Node head) {
        if (head == null) {
            return "#_";
        }
        String res = head.value + "_";
        res += serialByPre(head.left);
        res += serialByPre(head.right);
        return res;
    }

    /**
     * 有序列化后的字符串,进行反序列化,重构一棵树,然后该树的头节点
     *
     * @param serialString
     * @return
     */
    public static Node deSerialByPre(String serialString) {
        String[] values = serialString.split("_");
        Queue<String> queue = new LinkedList<String>();
        for (String value : values) {
            queue.offer(value);
        }
        return deSerialByPre(queue);
    }

    /**
     * 有二叉树的先序值序列,得到整颗二叉树的头结点
     *
     * @param queue
     * @return
     */
    private static Node deSerialByPre(Queue<String> queue) {
        String value = queue.poll();
        if ("#".equals(value)) {
            return null;
        }
        Node head = new Node(Integer.valueOf(value));
        head.left = deSerialByPre(queue);
        head.right = deSerialByPre(queue);
        return head;
    }

    public static void printTree(Node head) {
        System.out.println("Binary Tree:");
        printInOrder(head, 0, "H", 17);
        System.out.println();
    }

    public static void printInOrder(Node head, int height, String to, int len) {
        if (head == null) {
            return;
        }
        printInOrder(head.right, height + 1, "v", len);
        String val = to + head.value + to;
        int lenM = val.length();
        int lenL = (len - lenM) / 2;
        int lenR = len - lenM - lenL;
        val = getSpace(lenL) + val + getSpace(lenR);
        System.out.println(getSpace(height * len) + val);
        printInOrder(head.left, height + 1, "^", len);
    }

    public static String getSpace(int num) {
        String space = " ";
        StringBuffer buf = new StringBuffer("");
        for (int i = 0; i < num; i++) {
            buf.append(space);
        }
        return buf.toString();
    }

    public static void main(String[] args) {
        Node head = null;
        head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.right.right = new Node(5);


        printTree(head);
        String pre = serialByPre(head);
        System.out.println("serialize tree by pre-order: " + pre);
        head = deSerialByPre(pre);

        System.out.print("reconstruct tree by pre-order, ");
        printTree(head);
    }

    /**
     * Binary Tree:
     *                                          v5v       
     *                         v3v       
     *        H1H       
     *                         ^2^       
     *                                          ^4^       
     *
     * serialize tree by pre-order: 1_2_4_#_#_#_3_#_5_#_#_
     * reconstruct tree by pre-order, Binary Tree:
     *                                          v5v       
     *                         v3v       
     *        H1H       
     *                         ^2^       
     *                                          ^4^       
     */
}

 

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值