My C++ solution - easy to understand!!!


  • 0
    E
    class Codec {
    public:
    
        // Encodes a tree to a single string.
        string serialize(TreeNode* root) {
            string result;
            traverse(root, result);
            return result;
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            int start = 0;
            return helper(data, start);
        }
        
    private:
        void traverse(TreeNode* root, string& result) {
            if(result.size() != 0) {
                result.push_back(',');
            }
            if(root == NULL) {
                result += "NULL";
                return;
            }
            result += to_string(root -> val);
            traverse(root -> left, result);
            traverse(root -> right, result);
        }
        
        TreeNode* helper(string data, int& start) {
            if(start >= data.size()) {
                return NULL;
            }
            int index = data.find_first_of(',', start);
            if(index == string::npos) {
                index = data.size();
            }
            string tmp = data.substr(start, index - start);
            start = index + 1;
            if(tmp == "NULL") {
                return NULL;
            }
            TreeNode* root = new TreeNode(stoi(tmp));
            root -> left = helper(data, start);
            root -> right = helper(data, start);
            return root;
        }
    };

Log in to reply
 

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