public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
// If tree is empty just return a null string
if (root == null)
return "";
// BFS, saving nodes in the BST level by level
StringBuilder sb = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
sb.append(root.val + " ");
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode curr = queue.poll();
if (curr.left != null) {
queue.offer(curr.left);
sb.append(curr.left.val + " ");
}
else
sb.append("null" + " ");
if (curr.right != null) {
queue.offer(curr.right);
sb.append(curr.right.val + " ");
} else
sb.append("null" + " ");
}
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
// null tree when data length is 0
if (data.length() == 0)
return null;
// BFS, restore BST level by level
String[] dataArr = data.split(" "); // split the data by whitespace
TreeNode root = new TreeNode(Integer.parseInt(dataArr[0])); // first element in the dataArr is the root
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root); // put the root node into the queue
int i = 1; // a cursor to indicate which element in teh array should enqueue
while (!queue.isEmpty()) {
int size = queue.size(); // restore the tree level by level, we need a variable to save the size of current level
for (int k=0; k<size; k++) {
TreeNode curr = queue.poll();
// Restore left child
if (dataArr[i].equals("null")) {
curr.left = null;
} else {
curr.left = new TreeNode(Integer.parseInt(dataArr[i]));
queue.offer(curr.left);
}
i++;
// Restore right child
if (dataArr[i].equals("null")) {
curr.right = null;
} else {
curr.right = new TreeNode(Integer.parseInt(dataArr[i]));
queue.offer(curr.right);
}
i++;
}
}
return root;
}
}
Leetcode 449. Serialize and Deserialize BST
最新推荐文章于 2021-04-30 11:10:14 发布