AcWing 50. 序列化二叉树
原题链接
困难
作者:
小轩喵灬
,
2025-01-13 11:47:19
,
所有人可见
,
阅读 1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//50. 序列化二叉树
// Encodes a tree to a single string.
String serialize(TreeNode root) {
if (root == null) {
return "#";
}
return root.val + " " + serialize(root.left) + " " + serialize(root.right);
}
private String deserializeStr;
// Decodes your encoded data to tree.
TreeNode deserialize(String data) {
deserializeStr = data;
return deserialize();
}
private TreeNode deserialize() {
if (deserializeStr.length() == 0) {
return null;
}
int index = deserializeStr.indexOf(" ");
String node = index == -1 ? deserializeStr : deserializeStr.substring(0, index);
deserializeStr = index == -1? "" : deserializeStr.substring(index + 1);
if ("#".equals(node)) {
return null;
}
int val = Integer.parseInt(node);
TreeNode treeNode = new TreeNode(val);
treeNode.left = deserialize();
treeNode.right = deserialize();
return treeNode;
}
}