《程序员代码面试指南》第三章 二叉树问题 二叉树的序列化和反序列化

题目

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

java代码

package com.lizhouwei.chapter3;

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

/**
 * @Description:二叉树的序列化和反序列化
 * @Author: lizhouwei
 * @CreateDate: 2018/4/14 16:51
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter3_4 {

    //根据先序遍历序列二叉树
    public String serialTreeByPre(Node head) {
        if (head == null) {
            return "#!";
        }
        String res = head.value + "!";
        res += serialTreeByPre(head.left);
        res += serialTreeByPre(head.right);
        return res;
    }

    //反序列化
    public Node unSerialTreeByPre(String str) {
        if (str == null) {
            return null;
        }
        String[] strArr = str.split("!");
        Queue<String> queue = new LinkedList<String>();
        for (int i = 0; i < strArr.length; i++) {
            queue.offer(strArr[i]);
        }
        return recPreOrder(queue);
    }

    public Node recPreOrder(Queue<String> queue) {
        String value = queue.poll();
        if ("#".equals(value)) {
            return null;
        }
        Node head = new Node(Integer.valueOf(value));
        head.left = recPreOrder(queue);
        head.right = recPreOrder(queue);
        return head;
    }

    //测试
    public static void main(String[] args) {
        Chapter3_4 chapter = new Chapter3_4();
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        Node head = NodeUtil.generTree(arr, 0, arr.length - 1);
        String str = chapter.serialTreeByPre(head);
        System.out.print(str);
        System.out.println();
        Node head1 = chapter.unSerialTreeByPre(str);
        NodeUtil.preOrder(head1);
    }
}

转载于:https://www.cnblogs.com/lizhouwei/p/8832950.html

原文地址:https://www.cnblogs.com/twodog/p/12137115.html