C++ BFS + QUEUE


  • 0
    T
        string serialize(TreeNode* root) {
            string code = "";
            queue<TreeNode*> qnode;
            if (root) qnode.push(root);
            while (!qnode.empty()) {
                TreeNode *t = qnode.front(); qnode.pop();
                code += (t ? to_string(t->val):".")+" " ;
                if (t) {
                    qnode.push(t->left); qnode.push(t->right);
                }
            }
            return code;
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            stringstream ss(data);
            string tmp;
            if (!getline(ss, tmp, ' ') || tmp == ".") return nullptr;
            TreeNode *root = new TreeNode(stoi(tmp));
            queue<TreeNode*> qnode;
            qnode.push(root);
            while (getline(ss, tmp, ' ')) {
                TreeNode *t = qnode.front(); qnode.pop();
                if (tmp != ".") {
                    t->left = new TreeNode(stoi(tmp));
                    qnode.push(t->left);
                }
                getline(ss, tmp, ' ');
                if (tmp != ".") {
                    t->right = new TreeNode(stoi(tmp));
                    qnode.push(t->right);
                }
            }
            return root;
        }
    };
    

Log in to reply
 

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