# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassCodec:defserialize(self,root):"""Encodes a tree to a single string. :type root: TreeNode :rtype: str """ifrootisNone:return""q=deque([root])ans=[]whileq:node=q.popleft()ifnode:ans.append(str(node.val))q.append(node.left)q.append(node.right)else:ans.append("#")return",".join(ans)defdeserialize(self,data):"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ifnotdata:returnNonevals=data.split(",")root=TreeNode(int(vals[0]))q=deque([root])i=1whileq:node=q.popleft()ifvals[i]!="#":node.left=TreeNode(int(vals[i]))q.append(node.left)i+=1ifvals[i]!="#":node.right=TreeNode(int(vals[i]))q.append(node.right)i+=1returnroot# Your Codec object will be instantiated and called as such:# codec = Codec()# codec.deserialize(codec.serialize(root))
/** * 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.publicStringserialize(TreeNoderoot){if(root==null){returnnull;}List<String>ans=newArrayList<>();Deque<TreeNode>q=newLinkedList<>();q.offer(root);while(!q.isEmpty()){TreeNodenode=q.poll();if(node!=null){ans.add(node.val+"");q.offer(node.left);q.offer(node.right);}else{ans.add("#");}}returnString.join(",",ans);}// Decodes your encoded data to tree.publicTreeNodedeserialize(Stringdata){if(data==null){returnnull;}String[]vals=data.split(",");inti=0;TreeNoderoot=newTreeNode(Integer.valueOf(vals[i++]));Deque<TreeNode>q=newArrayDeque<>();q.offer(root);while(!q.isEmpty()){TreeNodenode=q.poll();if(!"#".equals(vals[i])){node.left=newTreeNode(Integer.valueOf(vals[i]));q.offer(node.left);}++i;if(!"#".equals(vals[i])){node.right=newTreeNode(Integer.valueOf(vals[i]));q.offer(node.right);}++i;}returnroot;}}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.deserialize(codec.serialize(root));
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */classCodec{public:// Encodes a tree to a single string.stringserialize(TreeNode*root){if(!root){return"";}queue<TreeNode*>q{{root}};stringans;while(!q.empty()){autonode=q.front();q.pop();if(node){ans+=to_string(node->val)+" ";q.push(node->left);q.push(node->right);}else{ans+="# ";}}ans.pop_back();returnans;}// Decodes your encoded data to tree.TreeNode*deserialize(stringdata){if(data==""){returnnullptr;}stringstreamss(data);stringt;ss>>t;TreeNode*root=newTreeNode(stoi(t));queue<TreeNode*>q{{root}};while(!q.empty()){autonode=q.front();q.pop();ss>>t;if(t!="#"){node->left=newTreeNode(stoi(t));q.push(node->left);}ss>>t;if(t!="#"){node->right=newTreeNode(stoi(t));q.push(node->right);}}returnroot;}};// Your Codec object will be instantiated and called as such:// Codec codec;// codec.deserialize(codec.serialize(root));
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */typeCodecstruct{}funcConstructor()Codec{returnCodec{}}// Serializes a tree to a single string.func(this*Codec)serialize(root*TreeNode)string{ifroot==nil{return""}q:=[]*TreeNode{root}ans:=[]string{}forlen(q)>0{node:=q[0]q=q[1:]ifnode!=nil{ans=append(ans,strconv.Itoa(node.Val))q=append(q,node.Left)q=append(q,node.Right)}else{ans=append(ans,"#")}}returnstrings.Join(ans,",")}// Deserializes your encoded data to tree.func(this*Codec)deserialize(datastring)*TreeNode{ifdata==""{returnnil}vals:=strings.Split(data,",")v,_:=strconv.Atoi(vals[0])i:=1root:=&TreeNode{Val:v}q:=[]*TreeNode{root}forlen(q)>0{node:=q[0]q=q[1:]ifx,err:=strconv.Atoi(vals[i]);err==nil{node.Left=&TreeNode{Val:x}q=append(q,node.Left)}i++ifx,err:=strconv.Atoi(vals[i]);err==nil{node.Right=&TreeNode{Val:x}q=append(q,node.Right)}i++}returnroot}/** * Your Codec object will be instantiated and called as such: * ser := Constructor(); * deser := Constructor(); * data := ser.serialize(root); * ans := deser.deserialize(data); */
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } *//** * Encodes a tree to a single string. * * @param {TreeNode} root * @return {string} */varserialize=function(root){if(!root)return'[]';letqueue=[root];letres='';while(queue.length){letnode=queue.shift();if(node){res+=node.val+',';queue.push(node.left);queue.push(node.right);}else{res+='null'+',';}}return`[${res.substring(0,res.length-1)}]`;};/** * Decodes your encoded data to tree. * * @param {string} data * @return {TreeNode} */vardeserialize=function(data){if(!data||data.length<=2)returnnull;letarr=data.substring(1,data.length-1).split(',');letroot=newTreeNode(arr.shift());letqueue=[root];while(queue.length){letnode=queue.shift();letleftVal=arr.shift();if(leftVal!=='null'){node.left=newTreeNode(leftVal);queue.push(node.left);}letrightVal=arr.shift();if(rightVal!=='null'){node.right=newTreeNode(rightVal);queue.push(node.right);}}returnroot;};/** * Your functions will be called as such: * deserialize(serialize(root)); */
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */publicclassCodec{publicstringserialize(TreeNoderoot){returnrserialize(root,"");}publicTreeNodedeserialize(stringdata){string[]dataArray=data.Split(",");LinkedList<string>dataList=newLinkedList<string>(dataArray.ToList());returnrdeserialize(dataList);}publicstringrserialize(TreeNoderoot,stringstr){if(root==null){str+="None,";}else{str+=root.val.ToString()+",";str=rserialize(root.left,str);str=rserialize(root.right,str);}returnstr;}publicTreeNoderdeserialize(LinkedList<string>dataList){if(dataList.First.Value.Equals("None")){dataList.RemoveFirst();returnnull;}TreeNoderoot=newTreeNode(int.Parse(dataList.First.Value));dataList.RemoveFirst();root.left=rdeserialize(dataList);root.right=rdeserialize(dataList);returnroot;}}// Your Codec object will be instantiated and called as such:// Codec codec = new Codec();// codec.deserialize(codec.serialize(root));
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */classCodec{public:stringempty="#";stringsep=",";// Encodes a tree to a single string.stringserialize(TreeNode*root){if(!root)returnempty+sep;stringres=to_string(root->val)+sep;res+=serialize(root->left);res+=serialize(root->right);returnres;}// Decodes your encoded data to tree.TreeNode*deserialize(stringdata){list<string>nodes;size_tpos=0;stringnode;while((pos=data.find(sep))!=string::npos){node=data.substr(0,pos);nodes.push_back(node);data.erase(0,pos+sep.length());}returndeserialize(nodes);}TreeNode*deserialize(list<string>&data){if(data.empty())returnnullptr;stringfirst=data.front();data.pop_front();if(first==empty)returnnullptr;TreeNode*root=newTreeNode(stoi(first));root->left=deserialize(data);root->right=deserialize(data);returnroot;}};// Your Codec object will be instantiated and called as such:// Codec codec;// codec.deserialize(codec.serialize(root));
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } *//** * Encodes a tree to a single string. * * @param {TreeNode} root * @return {string} */varserialize=function(root){if(root==null){return'#';}const{val,left,right}=root;return`${val},${serialize(left)},${serialize(right)}`;};/** * Decodes your encoded data to tree. * * @param {string} data * @return {TreeNode} */vardeserialize=function(data){constvals=data.split(',');letindex=0;constdfs=()=>{if(vals[index]=='#'){index++;returnnull;}constres=newTreeNode(vals[index++]);res.left=dfs();res.right=dfs();returnres;};returndfs();};/** * Your functions will be called as such: * deserialize(serialize(root)); */
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */classCodec{public:stringempty="#";stringsep=",";// Encodes a tree to a single string.stringserialize(TreeNode*root){if(!root)returnempty+sep;stringres="";res+=serialize(root->left);res+=serialize(root->right);res+=to_string(root->val)+sep;returnres;}// Decodes your encoded data to tree.TreeNode*deserialize(stringdata){vector<string>nodes;size_tpos=0;stringnode;while((pos=data.find(sep))!=string::npos){node=data.substr(0,pos);nodes.push_back(node);data.erase(0,pos+sep.length());}returndeserialize(nodes);}TreeNode*deserialize(vector<string>&nodes){if(nodes.empty())returnnullptr;stringfront=nodes.back();nodes.pop_back();if(front==empty)returnnullptr;TreeNode*root=newTreeNode(stoi(front));// 先构造右子树,后构造左子树root->right=deserialize(nodes);root->left=deserialize(nodes);returnroot;}};// Your Codec object will be instantiated and called as such:// Codec codec;// codec.deserialize(codec.serialize(root));