/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.*; publicclassCodec{
// Encodes a tree to a single string. public String serialize(TreeNode root){ List<Integer> list = new ArrayList<>(); if(root == null){ return list.toString(); }
// 宽度优先遍历 Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root);
String[] arr = str.split(","); List<Integer> list = new ArrayList<>(); for(String s : arr){ if(!"null".equals(s.trim())){ list.add(Integer.valueOf(s.trim())); }else{ list.add(null); } } int cur = 0; Integer val = list.get(cur++); TreeNode root = new TreeNode(val); Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while(!queue.isEmpty()){ TreeNode node = queue.poll();
if(node == null){ continue; }
if(cur == list.size() - 1){ break; }
Integer leftVal = list.get(cur++); TreeNode left = null; if(leftVal != null){ left = new TreeNode(leftVal); } node.left = left; queue.offer(left);
if(cur == list.size() - 1){ break; }
Integer rightVal = list.get(cur++); TreeNode right = null; if(rightVal != null){ right = new TreeNode(rightVal); } node.right = right; queue.offer(right); }
return root; } }
// Your Codec object will be instantiated and called as such: // Codec ser = new Codec(); // Codec deser = new Codec(); // TreeNode ans = deser.deserialize(ser.serialize(root));