标签:序列 code src col else cal decode 层序遍历 序列化
采用层序遍历的顺序,储存每一层的值,不存在的或者NULL值用#代替,每个位置以‘/‘结束
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { string res; queue<TreeNode*> q; q.push(root); int flag=1; while(flag){ flag=0; int k=q.size(); for(int i=0;i<k;i++){ TreeNode* p=q.front(); q.pop(); if(p==NULL){ res.push_back(‘#‘); q.push(NULL); q.push(NULL); }else{ int value=p->val; if(value<0) {res.push_back(‘-‘);value=-value;} stack<char> s; if(value==0) s.push(‘0‘); while(value){ int e=value%10; s.push(e+‘0‘);value=value/10; } while(!s.empty()){ res.push_back(s.top());s.pop(); } q.push(p->left); q.push(p->right); if(p->left||p->right) flag=1; } res.push_back(‘/‘); } } cout<<res<<endl; return res; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if(data.size()==0) return NULL; if(data.size()==2&&data[0]==‘#‘)return NULL; int len=data.size(); vector<TreeNode*> v; for(int i=0;i<len;i++){ if(data[i]==‘/‘)continue; TreeNode* p=NULL; if(data[i]!=‘#‘){ int value=0; int flag=1; if(data[i]==‘-‘) {flag=-1;i++;} while(data[i]!=‘/‘){ value=10*value+data[i]-‘0‘; i++; } value=flag*value; p=new TreeNode(value); } v.push_back(p); } for(int i=0;i<(v.size()-1)/2;i++){ if(v[i]!=NULL){ v[i]->left=v[2*i+1]; v[i]->right=v[2*i+2]; } } return v[0]; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));
测试例子如下:
样例通过为47/48,一个深度为1000的偏二叉树没有通过;
标签:序列 code src col else cal decode 层序遍历 序列化
原文地址:https://www.cnblogs.com/joelwang/p/10938289.html