import java.util.*; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { int INF = 1000; TreeNode emptyNode = new TreeNode(INF); String Serialize(TreeNode root) { if (root == null)return ""; Queue<TreeNode> q = new LinkedList<>(); q.add(root); StringBuilder sb = new StringBuilder(); while (!q.isEmpty()) { TreeNode cur = q.poll(); sb.append(cur.val + "#"); if (!cur.equals(emptyNode)) { q.add(cur.left == null ? emptyNode : cur.left); q.add(cur.right == null ? emptyNode : cur.right); } } return sb.toString(); } TreeNode Deserialize(String str) { if (str == "")return null; String[] s = str.split("#"); TreeNode root = new TreeNode(Integer.parseInt(s[0])); Queue<TreeNode> q = new LinkedList<>(); q.add(root); for (int i = 1; i < s.length; i += 2) { TreeNode cur = q.poll(); int left = Integer.parseInt(s[i]), right = Integer.parseInt(s[i + 1]); if (left != INF) { cur.left = new TreeNode(left); q.add(cur.left); } if (right != INF) { cur.right = new TreeNode(right); q.add(cur.right); } } return root; } }
利用层序遍历,使用队列解决