二叉树序列化和反序列化
Posted moris5013
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树序列化和反序列化相关的知识,希望对你有一定的参考价值。
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.right.right = new Node(7); root.left.right.left = new Node(8); root.left.right.right = new Node(9); //序列化二叉树, null用#表示,每个节点之间用_分隔 String str = serialize(root); System.out.println(str); //反序列化 Node node = deserialize(str); //验证反序列 的结果对不对 System.out.println(serialize(node)); } public static Node deserialize(String str) { String[] split = str.split("_"); Queue<String> queue = new LinkedList<>(); for (String s : split) { queue.offer(s); } return setp(queue); } public static Node setp(Queue<String> queue) { String str = queue.poll(); if (str.equals("#")) { return null; } Node root = new Node(Integer.parseInt(str)); root.left = setp(queue); root.right = setp(queue); return root; } public static String serialize(Node root) { if (root == null) { return "#_"; } String selfStr = root.value + "_"; String leftStr = serialize(root.left); String rightStr = serialize(root.right); return selfStr + leftStr + rightStr; } public static class Node { Node left; Node right; int value; public Node(int value) { this.value = value; } } }
以上是关于二叉树序列化和反序列化的主要内容,如果未能解决你的问题,请参考以下文章