serialize-and-deserialize-bst
https://leetcode.com/problems/serialize-and-deserialize-bst/
1. 用到Java Queue接口,
// LinkedList实现了Queue接口, ArrayList没有实现
2. 用的Java String.split 函数得到 String数组。
3. 另外一个bug是因为String比较用的 == ,没有用 equals
package com.company; import apple.laf.JRSUIUtils; import java.util.*; class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } class Codec { // Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuilder sb = new StringBuilder(); if (root == null) { return ""; } // LinkedList实现了Queue接口, ArrayList没有实现 Queue<TreeNode> qe= new LinkedList<>(); qe.offer(root); sb.append(root.val+","); while (!qe.isEmpty()) { TreeNode tn = qe.poll(); if (tn.left != null) { sb.append(tn.left.val+","); qe.offer(tn.left); } else { sb.append(","); } if (tn.right != null) { sb.append(tn.right.val+","); qe.offer(tn.right); } else { sb.append(","); } } return sb.toString(); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if (data.equals("")) { return null; } String[] strs = data.split(","); Queue<TreeNode> qe = new LinkedList<>(); if (strs.length < 1 || strs[0].equals("")) { return null; } TreeNode root = new TreeNode(Integer.valueOf(strs[0])); qe.offer(root); int i = 1; while (!qe.isEmpty()) { TreeNode tn = qe.poll(); if (strs.length > i && !strs[i].equals("")) { TreeNode left = new TreeNode(Integer.valueOf(strs[i])); tn.left = left; qe.offer(left); } i++; if (strs.length > i && !strs[i].equals("")) { TreeNode right = new TreeNode(Integer.valueOf(strs[i])); tn.right = right; qe.offer(right); } i++; } return root; } } public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("Hello!"); //Solution solution = new Solution(); // Your Codec object will be instantiated and called as such: TreeNode tn = new TreeNode(2); TreeNode tn1 = new TreeNode(1); //TreeNode tn2 = new TreeNode(3); tn.left = tn1; //tn.right = tn2; Codec codec = new Codec(); String code = codec.serialize(tn); System.out.printf("code:%s\n", code); TreeNode ret = codec.deserialize(code); System.out.printf("root:%d\n", ret.val); System.out.println(); } }