/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ publicclassCodec{
// Encodes a tree to a single string. public String serialize(TreeNode root){ if(root==null){ return""; } //非递归解法 Queue<TreeNode> queue = new LinkedList<>(); StringBuilder res = new StringBuilder(); //根节点入队列 queue.offer(root); while(!queue.isEmpty()){ //出队,判断 TreeNode out = queue.poll(); if(out!=null){ res.append(out.val+","); //将左右添加进来 queue.add(out.left); queue.add(out.right); }else{ res.append("null,"); } } return res.toString(); }
// Decodes your encoded data to tree. public TreeNode deserialize(String data){ if(data.isEmpty()){ returnnull; } String[] nodes = data.split(","); //层次遍历第一个还是根节点 TreeNode root = new TreeNode(Integer.parseInt(nodes[0])); //反序列化还是队列 Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root);
// Encodes a tree to a single string. public String serialize(TreeNode root){ StringBuilder sb = new StringBuilder(); serialize(root,sb); return sb.toString(); } //辅助函数 voidserialize(TreeNode root,StringBuilder sb){ if(root==null){ sb.append("null,"); return; } //前序遍历 sb.append(root.val+","); serialize(root.left,sb); serialize(root.right,sb); }
// Decodes your encoded data to tree. public TreeNode deserialize(String data){ //将字符串,拆成链表 LinkedList<String> node = new LinkedList<>(); for (String s : data.split(",")){ node.addLast(s); } return deserialize(node); } //辅助函数 TreeNode deserialize(LinkedList<String> node){ if(node.isEmpty()){ returnnull; } //根据前序遍历特点排列节点 String node1 = node.removeFirst(); if(node1.equals("null")){ returnnull; } //将第一个节点还原 TreeNode root = new TreeNode(Integer.parseInt(node1)); //这里不是很理解 root.left = deserialize(node); root.right = deserialize(node); return root; } }