C++ solution: pre-order using stack


  • 0
    H
    class Codec {
    public:
    
        // Encodes a tree to a single string.
        string serialize(TreeNode* root) {
            string data;
            char buf[4];
            stack<TreeNode*> s;
            if (root) s.push(root);
            TreeNode* cur; 
            while (!s.empty()) {
                cur = s.top();
                s.pop();
                memcpy(buf, &(cur->val), sizeof(int));
                for (int i = 0; i < 4; ++i) data += buf[i];
                if (cur->right) s.push(cur->right);
                if (cur->left) s.push(cur->left);
            }
            return data;
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            if (!data.size()) return nullptr;
            int val;
            stack<TreeNode*> s;
            memcpy(&val, &data[0], sizeof(int));
            TreeNode* root = new TreeNode(val);
            s.push(root);
            TreeNode* cur;
            for (int i = 4; i < data.size(); i += 4) {
                memcpy(&val, &data[i], sizeof(int));
                if (val < s.top()->val) {
                    s.push(s.top()->left = new TreeNode(val));
                } else {
                    while(!s.empty() && val > s.top()->val ) {
                        cur = s.top();
                        s.pop();
                    }
                    s.push(cur->right =  new TreeNode(val));
                }
            }
            return root;
        }
    };
    

Log in to reply
 

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