/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/import java.util.LinkedList;import java.util.Queue;publicclassCodec{// Encodes a tree to a single string.public String serialize(TreeNode root){//层序遍历
StringBuffer ss =newStringBuffer("");
Queue<TreeNode> queue =newLinkedList<>();
queue.offer(root);while(!queue.isEmpty()){
TreeNode node = queue.poll();if(node==null){
ss= ss.append("null,");continue;}else ss.append(""+node.val+",");
queue.offer(node.left);
queue.offer(node.right);}return ss.toString();}// Decodes your encoded data to tree.public TreeNode deserialize(String data){if(data==null||data.equals("null,"))return null;
Queue<TreeNode> queue =newLinkedList<>();
String[] slist = data.split(",");
TreeNode root =newTreeNode(Integer.parseInt(slist[0]));
queue.offer(root);int i=1;while(i<slist.length){
TreeNode node = queue.poll();if(node!=null){//左儿子if(slist[i].equals("null"))node.left=null;else{
TreeNode leftNode =newTreeNode(Integer.parseInt(slist[i]));
node.left=leftNode;
queue.offer(leftNode);}//右儿子
i++;if(slist[i].equals("null"))node.right=null;else{
TreeNode rightNode =newTreeNode(Integer.parseInt(slist[i]));
node.right=rightNode;
queue.offer(rightNode);}
i++;}}return root;}}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.deserialize(codec.serialize(root));
然后是bfs 其实就是先序遍历。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/import java.util.LinkedList;import java.util.Queue;publicclassCodec{// Encodes a tree to a single string.publicvoiddfs(TreeNode node, StringBuffer ss){if(node==null){
ss.append("null,");return;}
ss.append(""+node.val+',');dfs(node.left,ss);dfs(node.right,ss);return;}public String serialize(TreeNode root){//先序遍历 dfs;
StringBuffer ss =newStringBuffer("");dfs(root,ss);return ss.toString();}public TreeNode dfs2(String[] slist,int[] index){if(index[0]>=slist.length||slist[index[0]].equals("null")){
index[0]++;return null;}
TreeNode node =newTreeNode(Integer.parseInt(slist[index[0]]));
index[0]++;
node.left=dfs2(slist,index);
node.right=dfs2(slist,index);return node;}// Decodes your encoded data to tree.public TreeNode deserialize(String data){if(data==null||data.equals("null,"))return null;returndfs2(data.split(","),newint[]{0});}}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.deserialize(codec.serialize(root));