297.serialize-and-deserialize-binary-tree.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import java.util.LinkedList;
  2. /**
  3. * Definition for a binary tree node.
  4. * public class TreeNode {
  5. * int val;
  6. * TreeNode left;
  7. * TreeNode right;
  8. * TreeNode(int x) { val = x; }
  9. * }
  10. */
  11. public class Codec {
  12. // Encodes a tree to a single string.
  13. public String serialize(TreeNode root) { // Level-order traversal
  14. StringBuilder sb = new StringBuilder();
  15. LinkedList<TreeNode> list = new LinkedList<TreeNode>();
  16. list.add(root);
  17. TreeNode curr;
  18. while (!list.isEmpty()) {
  19. curr = list.poll();
  20. if (curr == null) {
  21. sb.append("null,");
  22. continue;
  23. }
  24. sb.append(curr.val);
  25. sb.append(',');
  26. list.add(curr.left);
  27. list.add(curr.right);
  28. }
  29. sb.deleteCharAt(sb.length()-1); // Remove the last ','
  30. return sb.toString();
  31. }
  32. // Decodes your encoded data to tree.
  33. public TreeNode deserialize(String data) {
  34. String[] strs = data.split(",");
  35. if (strs[0].equals("null")) return null; // Root is null
  36. TreeNode root = new TreeNode(Integer.parseInt(strs[0]));
  37. LinkedList<TreeNode> list = new LinkedList<TreeNode>();
  38. list.add(root);
  39. int idx = 1;
  40. while (!list.isEmpty()) {
  41. TreeNode curr = list.poll();
  42. if (idx < strs.length) {
  43. if (!strs[idx].equals("null")) {
  44. curr.left = new TreeNode(Integer.parseInt(strs[idx]));
  45. list.add(curr.left);
  46. }
  47. idx++;
  48. }
  49. if (idx < strs.length) {
  50. if (!strs[idx].equals("null")) {
  51. curr.right = new TreeNode(Integer.parseInt(strs[idx]));
  52. list.add(curr.right);
  53. }
  54. idx++;
  55. }
  56. }
  57. return root;
  58. }
  59. }
  60. // Your Codec object will be instantiated and called as such:
  61. // Codec codec = new Codec();
  62. // codec.deserialize(codec.serialize(root));