题解 | #序列化二叉树#
序列化二叉树
https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { int index = -1; String Serialize(TreeNode root) { StringBuilder sb = new StringBuilder(); if (root == null) { sb.append("#,"); return sb.toString(); } sb.append(root.val + ","); sb.append(Serialize(root.left)); sb.append(Serialize(root.right)); return sb.toString(); } TreeNode Deserialize(String str) { index++; String[] strs = str.split(","); TreeNode node = null; if (!strs[index].equals("#")) { node = new TreeNode(Integer.valueOf(strs[index])); node.left = Deserialize(str); node.right = Deserialize((str)); } return node; } }
解题思想:
* 序列化:使调⽤前序遍历,也就是先遍历根节点,然后再遍历左左节点,右节点,使⽤递归即可。如果为空,则⽤“ # ”代替,两者之间使⽤“ , ”分割。
* 反序列化:按照逗号“ , ”分割,使⽤index作为索引标识,每次 +1 ,同样使⽤递归,先是根节点,再到左节点,再到右节点。
#算法##算法笔记#