MENU

LeetCode297. 二叉树的序列化与反序列化

August 9, 2018 • Read: 3568 • LeetCode阅读设置

题目链接:LeetCode297展开目录

题解展开目录

先序遍历、中序遍历、后序遍历进行序列化,然后同样的方式反序列化就行

代码展开目录
  • /**
  • * Definition for a binary tree node.
  • * public class TreeNode {
  • * int val;
  • * TreeNode left;
  • * TreeNode right;
  • * TreeNode(int x) { val = x; }
  • * }
  • */
  • public class Codec {
  • // Encodes a tree to a single string.
  • public String res = "";
  • public String serialize(TreeNode root) {
  • if(root == null)
  • return "null,";
  • String res = root.val + ",";
  • res += serialize(root.left);
  • res += serialize(root.right);
  • return res;
  • }
  • // Decodes your encoded data to tree.
  • public TreeNode deserialize(String data) {
  • String[] values = data.split(",");
  • Queue<String> queue = new LinkedList<String>();
  • for(int i = 0;i != values.length;i++)
  • queue.offer(values[i]);
  • return Back_Tree(queue);
  • }
  • public TreeNode Back_Tree(Queue<String> queue) {
  • String value = queue.poll();
  • if(value.equals("null"))
  • return null;
  • TreeNode head = new TreeNode(Integer.valueOf(value));
  • head.left = Back_Tree(queue);
  • head.right = Back_Tree(queue);
  • return head;
  • }
  • }
  • // Your Codec object will be instantiated and called as such:
  • // Codec codec = new Codec();
  • // codec.deserialize(codec.serialize(root));
Last Modified: November 25, 2018
Archives Tip
QR Code for this page
Tipping QR Code