C++ very straight forward level traval using stringstream to input


  • 2
    J
    class Codec {
    public:
    
        // Encodes a tree to a single string.
        string serialize(TreeNode* root) {
            if(!root)return "[]";
    
            string res="";
            queue<TreeNode*> q;
    
            q.push(root->left);
            q.push(root->right);            
    
    
            res=to_string(root->val);
            while(!q.empty()){
                TreeNode* p=q.front();
                q.pop();
                if(p)
                {
                    res=res+','+to_string(p->val);
    
                    q.push(p->left);
                    q.push(p->right);
    
                }
                else
                    res=res+','+'#';
    
            }
            res='['+res+']';
            return res;
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            TreeNode* root;
            queue<TreeNode*> q;
            string val;
            stringstream io(data.substr(1,data.length()-2));
    
            if(!getline(io,val,','))return NULL;
    
            TreeNode* tmp=new TreeNode(atoi(val.c_str()));
            q.push(tmp);
            root=tmp;
            
            while(!q.empty()){
                TreeNode* p=q.front();
                q.pop();  
                
               
                if(!getline(io,val,','))break;
                if(val!="#"){
                    tmp=new TreeNode(atoi(val.c_str()));
                    q.push(tmp);
                    p->left=tmp;
                }
                
                if(!getline(io,val,','))break;
                if(val!="#"){
                    tmp=new TreeNode(atoi(val.c_str()));
                    q.push(tmp);
                    p->right=tmp;
                }
                
            }
    
            
            return root;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.