C++ solution using DFS and istringstream


  • 3
    class Codec {
    private:
        TreeNode* de(istringstream& iss) {
            TreeNode* root = NULL;
            string word;
            if (iss >> word && word != "N") {
                root = new TreeNode(stoi(word));
                root->left = de(iss);
                root->right = de(iss);
            }
            return root;
        }
        
    public:
    
        // Encodes a tree to a single string.
        string serialize(TreeNode* root) {
            if (!root) { return "N "; }
            return to_string(root->val) + " " + serialize(root->left) + serialize(root->right);
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            istringstream iss(data);
            return de(iss);
        }
    };
    

  • 0

    The best C++ solution so far I've seen.


Log in to reply
 

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