zoukankan      html  css  js  c++  java
  • 《程序员代码面试指南》第三章 二叉树问题 二叉树的序列化和反序列化

    题目

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

    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);
        }
    }
    
  • 相关阅读:
    System.IO命名空间
    Java调用Http/Https接口(8,end)OkHttp调用Http/Https接口
    javascript上传组件
    在ubuntu下安装MonoDevelop
    Sql Server中Null+nvarchar结果为null
    利用iframe实现javascript无刷新载入整页
    C#序列化和反序列化
    vmware7.0下搭建ubuntuNat上网/C++开发环境
    javascript模态窗口Demo
    为博客添加在线台湾卫星电视播放功能
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8832950.html
Copyright © 2011-2022 走看看