Short C++ solution, using stringstreams and preorder traversal


  • 0
    A

    Short C++ solution, using stringstreams and preorder traversal:

    class Codec {
    public:
        string serialize(TreeNode* root) {
            ostringstream ss;
            tostr(root, ss);
            return ss.str();
        }
        
        void tostr(TreeNode* node, ostringstream &ss) {
            if (node == NULL) { ss << "NULL "; return; }
            ss << node->val << ' ';
            tostr(node->left, ss);
            tostr(node->right, ss);
        }
    
        TreeNode* deserialize(string data) {
            istringstream ss(data)
            return fromstr(ss);
        }
        
        TreeNode* fromstr(istringstream &ss) {
            string s; ss >> s;
            if (s == "NULL") return NULL;
            auto node = new TreeNode(stoi(s));
            node->left = fromstr(ss);
            node->right = fromstr(ss);
            return node;
        }    
    };
    

Log in to reply
 

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