/* 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) { if(root == null){ return "#!"; } //前序遍历生成字符串 return root.val+"!"+Serialize(root.left)+Serialize(root.right); } TreeNode Deserialize(String str) { return str2tree(str.split("!")); } private int pos = 0; TreeNode str2tree(String[] arr){ if(pos >= arr.length){ return null; } if(arr[pos].equals("#")){ return null; } TreeNode node = new TreeNode(Integer.valueOf(arr[pos])); //左节点位置++ pos++; node.left = str2tree(arr); //右节点位置++ pos++; node.right = str2tree(arr); return node; } }
原文:https://www.cnblogs.com/MoonBeautiful/p/13122221.html