https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/submissions/
开始看题没审题,以为要像案例那样使用层序遍历,导致代码超时
改用先序遍历之后,代码简洁不少,也不超时
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
doS(root, sb);
return sb.toString();
}
private void doS(TreeNode root, StringBuilder sb) {
if (root == null) {
sb.append("n,");
return;
}
sb.append(root.val);
sb.append(",");
doS(root.left, sb);
doS(root.right, sb);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] datas = data.split(",");
if ("n".equals(datas[0])) {
return null;
}
int len = datas.length;
TreeNode root = doS(datas, len - 1);
return root;
}
int k = 0;
private TreeNode doS(String[] datas, int len) {
if (k >= len) {
return null;
}
if ("n".equals(datas[k])) {
k++;
return null;
}
TreeNode node = new TreeNode(Integer.parseInt(datas[k]));
k++;
node.left = doS(datas, len);
node.right = doS(datas, len);
return node;
}
如果有leetcode不明白的题目,欢迎评论,一起探讨