二叉树序列化

普通二叉树的序列化和反序列化:

先序遍历,null节点用特殊符号标记。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;

public class Solution {

    public static void serialize(TreeNode root, PrintStream ps) {
        if (root == null)
            ps.print("# ");
        else {
            ps.print(root.val + " ");
            serialize(root.left, ps);
            serialize(root.right, ps);
        }
    }

    public static TreeNode deserialize(Scanner cin) {
        String token = cin.next();
        if (token.equals("#"))
            return null;
        int val = Integer.parseInt(token);
        TreeNode root = new TreeNode(val);
        root.left = deserialize(cin);
        root.right = deserialize(cin);

        return root;

    }

    public static void main(String[] args) throws FileNotFoundException {
        TreeNode root = new TreeNode(30);
        root.left = new TreeNode(20);
        root.left.left = new TreeNode(10);
        root.right = new TreeNode(40);
        root.right.left = new TreeNode(35);
        root.right.right = new TreeNode(50);
        PrintStream ps = new PrintStream(new File("serialize.txt"));
        serialize(root, ps);

        Scanner cin = new Scanner(new File("serialize.txt"));
        TreeNode back = deserialize(cin);

        System.out.println(back.val);

    }
}

BST的序列化和反序列化:

序列化:直接先序遍历输出

反序列化:根据先序遍历构造。O(n)时间。

import java.io.FileNotFoundException;
import java.util.Scanner;

public class Solution {

    private static int curVal;

    public static TreeNode deserializeBSTfromInorder(Scanner cin) {
        if (!cin.hasNext())
            return null;
        else {
            curVal = cin.nextInt();
            return deserialize(cin, Integer.MIN_VALUE, Integer.MAX_VALUE);
        }
    }

    private static TreeNode deserialize(Scanner cin, int min, int max) {
        if (curVal > min && curVal < max) {
            int val = curVal;
            TreeNode root = new TreeNode(val);
            if (cin.hasNext()) {
                curVal = cin.nextInt();
                root.left = deserialize(cin, min, val);
                root.right = deserialize(cin, val, max);
            }

            return root;
        } else
            return null;
    }

    public static void main(String[] args) throws FileNotFoundException {
        String s = "30 20 10 40 35 50";
        Scanner cin = new Scanner(s);
        TreeNode back = deserializeBSTfromInorder(cin);

        System.out.println(back.val);

    }

}

从数组度数据:

public class Solution {

    private int curr;

    public TreeNode deserialize(int[] preorder) {
        curr = 0;
        return deserialize(preorder, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }

    public TreeNode deserialize(int[] preorder, int min, int max) {
        if (curr >= preorder.length || preorder[curr] <= min || preorder[curr] >= max) {
            return null;
        }

        int val = preorder[curr++];
        TreeNode root = new TreeNode(val);
        root.left = deserialize(preorder, min, val);
        root.right = deserialize(preorder, val, max);

        return root;

    }

    public static void main(String[] args) {
        int[] pre = new int[] { 30, 20, 10, 40, 35, 50 };
        TreeNode root = new Solution().deserialize(pre);

        System.out.println(root);
    }

}

参考:

http://leetcode.com/2010/09/saving-binary-search-tree-to-file.html

http://leetcode.com/2010/09/serializationdeserialization-of-binary.html

时间: 2024-10-11 19:24:35

二叉树序列化的相关文章

二叉树序列化和反序列化

public class BinaryTreeSerialize { public static void main(String[] args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.r

剑指offer:序列化二叉树

题目描述请实现两个函数,分别用来序列化和反序列化二叉树 # -*- coding: utf-8 -*- # @Time : 2019-07-07 15:48 # @Author : Jayce Wong # @ProjectName : job # @FileName : serializeBinaryTree.py # @Blog : https://blog.51cto.com/jayce1111 # @Github : https://github.com/SysuJayce class

数据结构总结

剑指OfferJAVA版 1.      排序算法 稳定性的概念: 假定待排序的记录序列中,存在多个具有相同的关键字的记录,若经过排序,这些记录的相对次序保持不变,称这种排序算法是稳定的,否则称为不稳定的. package com.ljl.sort; import org.junit.Test; /** * 七大排序算法 * @author acer * */ public class Sort { private int[] unsorted={1,3,2,8,9,7,6,6,5,3,4};

Lintcode7 Binary Tree Serialization solution 题解

[题目描述] Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'. 设计一个算法,并编写代码来序列化

【LeetCode】Unique Binary Search Trees II 不同的二叉查找树II

今早起来做 LeetCode,结果被这道题卡了将近1个半小时,忍着没有去搜答案,最后还是被我想出来了,而且直接一次AC,哈哈!现在在这里记录一下解题思路. 原题: Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example,Given n = 3, your program should return all 5 unique BST's sh

刷题笔记 - 0422

1.clone graph   用map结构存储原值和拷贝值,一一对应. map红黑树实现,O(logn) 内部有序:每个节点要保存父节点.子节点及红黑属性,占用空间大. unordered_map哈希表实现,查找O(1),内部无序:哈希表建立耗时.   常用unordered_map class Solution { public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { // 拷贝所有点 DFS写法 if (!

2019.10.27 头条面试准备

2019.10.27 头条面试准备 个人简历 2019.06 - 至今上海华为开发工程师 实习部门:5G开发部 项目:网站开发.运维开发.数据处理 2019.06至今华为实习 Python+Django+Javascript+Nginx+rabbitMQ+ELK 基于 Django 框架使用 Python 开发网站基础进程监控系统,实现进程异常记录.进程异常自动恢复.发送告警邮件,并且用 Web 界面进行展示和管理.整个框架由本人独立设计完成并上线,保证了部门 Web 的稳定. 使用Python

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

http://blog.csdn.net/qq_27703417/article/details/70958692 先序遍历二叉树,如果遇到空节点,就在str的末尾加上"#!","#"表示这个节点为空,节点值不存在,当然你也可以用其他的特殊字符,"!"表示一个值的结束.如果遇到不为空的节点,假设节点值为3,就在str的末尾加上"3!".现在请你实现树的先序序列化. 先序遍历 import java.util.*; //使用递归

序列化二叉树-剑指Offer

序列化二叉树 题目描述 请实现两个函数,分别用来序列化和反序列化二叉树 思路 序列化就按先序遍历,遇到空指针也要存下来,递归调用,StringBuilder 反序列化是同样的递归调用,不过要考虑参数的传递,生成的TreeNode要返回 注意:对Sting[]的遍历,每次递归都要往后遍历一个字符,如果将这个位置信息point通过参数传入的话,就会造成函数无法正常遍历String[],此时,我们可以将位置信息设置为类的成员变量,每次递归时都要递增,这样既可满足条件 代码 /* public clas