题解 | #序列化二叉树#
序列化二叉树
https://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
import java.util.*; import java.lang.*; /* 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 builder = new StringBuilder(); getString(root, builder); return builder.toString(); } private void getString(TreeNode root, StringBuilder builder) { if (root == null) { builder.append(","); } else { builder.append(root.val).append(","); getString(root.left, builder); getString(root.right, builder); } } TreeNode Deserialize(String str) { String[] strArray = str.split( ","); int[] ptr = new int[] {0}; return dfs(strArray, ptr); } private TreeNode dfs(String[] strArray, int[] ptr) { if (ptr[0] >= strArray.length || strArray[ptr[0]].length() == 0) { ptr[0]++; return null; } TreeNode node = new TreeNode(Integer.parseInt(strArray[ptr[0]++])); node.left = dfs(strArray, ptr); node.right = dfs(strArray, ptr); return node; } }