C++ straightforward preorder approach


  • 0
    S
    class Codec {
    public:
    
        // Encodes a tree to a single string.
        string serialize(TreeNode* root) {
            string res;
            traverse(root, res);
            return res;
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            int pos = 0;
            return dfs_create(data, pos);
        }
        
    private:
        void traverse(TreeNode* root, string& res) {
            if (!res.empty()) {
                res.push_back(',');
            }
            
            if (root == NULL) {
                res += "null";
                return;
            }
            
            res += to_string(root->val);
            traverse(root->left, res);
            traverse(root->right, res);
        }
    
        TreeNode* dfs_create(string data, int& pos) {
             if (pos >= data.size()) return NULL;
            
            int pos1 = data.find_first_of(",", pos);
            if (pos1 == string::npos) {
                pos1 = data.size();
            }
            
            TreeNode* root;
            string vals = data.substr(pos, pos1-pos);
            pos = pos1 + 1;
            if(vals == "null") {
                root = NULL;
                return root;
            } 
            
            int val = atoi(vals.c_str());
            root = new TreeNode(val);
            
            root->left = dfs_create(data, pos);
            root->right = dfs_create(data, pos);
            return root;
        }
    };

Log in to reply
 

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