請實現兩個函數,分別用來序列化和反序列化二叉樹java
什麼是序列化?
能夠理解爲一直存儲結構
序列化後還要能夠反序列化
對於樹的序列號,能夠理解爲層次遍歷,可是也要記錄其中的空結點,這是爲了可以回去app
class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public class Solution3 { public String Serialize(TreeNode root) { if(root == null) return ""; StringBuilder sb = new StringBuilder(); Serialize(root, sb); return sb.toString(); } private void Serialize(TreeNode root, StringBuilder sb) { if(root == null) { sb.append("#,"); return; } sb.append(root.val); sb.append(','); Serialize(root.left, sb); Serialize(root.right, sb); } int index = -1; public TreeNode Deserialize(String str) { if(str.length() == 0) return null; String[] strs = str.split(","); return Deserialize(strs); } private TreeNode Deserialize(String[] strs) { index++; if(!strs[index].equals("#")) { TreeNode root = new TreeNode(0); root.val = Integer.parseInt(strs[index]); root.left = Deserialize(strs); root.right = Deserialize(strs); return root; } return null; } public static void main(String[] args) { Solution3 s3 = new Solution3(); /** * 構造二叉樹 * 1 * / \ * 2 3 * / \ / \ * 4 5 6 7 */ TreeNode root = new TreeNode(1); TreeNode left = new TreeNode(2); TreeNode right = new TreeNode(3); TreeNode left_1 = new TreeNode(4); TreeNode right_1 = new TreeNode(5); TreeNode right_2 = new TreeNode(6); TreeNode left_2 = new TreeNode(7); left.left = left_1; left.right = right_1; right.left = left_2; right.right = right_2; root.left = left; root.right = right; //System.out.println(s3.Serialize(root));//輸出:1,2,4,#,#,5,#,#,3,7,#,#,6,#,#, System.out.println(s3.Deserialize("1,2,4,#,#,5,#,#,3,7,#,#,6,#,#,").left.val);//輸出:2 } }