序列化二叉树-Java
序列化二叉树
http://www.nowcoder.com/questionTerminal/cf7e25aa97c04cc1a68c8f040e71fb84
一. 思路
序列化:将树转成字串
反序列化:将字串转成树
因此序列化其实就是遍历树,可采用BFS层次遍历,用队列LinkedList实现。
反序列就是根据序列化的过程去解析。
注意:必须注意反序列化时,对字串中特殊符号的转换要注意是否符合Java类型转换原则
二. 代码
import java.util.*; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { /** * 采用层次遍历解决 */ String Serialize(TreeNode root) { StringBuilder str = new StringBuilder(); Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (node == null) { str.append(",#"); continue; } str.append("," + node.val); //叶子节点直接跳过此次循环 if (node.left == null && node.right == null) continue; queue.offer(node.left); queue.offer(node.right); } return str.substring(1); } TreeNode Deserialize(String str) { String[] treeStr = str.split(","); Queue<TreeNode> queue = new LinkedList<>(); int index = 0; //获取根节点 TreeNode root = null; if (!"#".equals(treeStr[index])) { root = new TreeNode(Integer.parseInt(treeStr[index])); } queue.offer(root); while (!queue.isEmpty() && index < treeStr.length-1) { TreeNode node = queue.poll(); if (node == null) continue; index++; if (!"#".equals(treeStr[index])) { //构造左子树 node.left = new TreeNode(Integer.parseInt(treeStr[index])); } index++; if (!"#".equals(treeStr[index])) { //构造右子树 node.right = new TreeNode(Integer.parseInt(treeStr[index])); } queue.offer(node.left); queue.offer(node.right); } return root; } }