Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Codec {
- // Encodes a tree to a single string.
- public String serialize(TreeNode root) {
- test = root;
- String result = "[";
- if (root == null) return result + "]";
- Queue<TreeNode> q = new LinkedList<>();
- q.add(root);
- while (!q.isEmpty()) {
- int preSize = q.size();
- for (int i = 0; i < preSize; i++) {
- TreeNode curr = q.poll();
- if (curr == null) {
- result += "null,";
- } else {
- result += curr.val + ",";
- q.add(curr.left);
- q.add(curr.right);
- }
- }
- }
- int firstIdx = result.length() - 5;
- while (result.substring(firstIdx, result.length()).equals("null,")) {
- firstIdx -= 5;
- }
- return result.substring(0, firstIdx - 1) + "]";
- }
- //[1,2,null,null,
- // Decodes your encoded data to tree.
- public TreeNode deserialize(String data) {
- return test;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement