3
// Returns the index of '-' if present otherwise returns the string length4
int findIndex(int ind, string &traversal) {5
int req = traversal.size();6
for (int i = ind; i < traversal.size(); i++) {7
if (traversal[i] == '-') {15
TreeNode *recoverFromPreorder(string traversal) {16
// Pushing the node along with its depth into the stack18
stack<pair<TreeNode *, int>> st;20
// Finding the root node21
int ind = findIndex(0, traversal);22
string str = traversal.substr(0, ind);23
TreeNode *root = new TreeNode(stoi(str));25
// Pushing the root node along with its depth28
// Starting from 'ind' as it has the next '-' character31
while (i < traversal.size()) {32
// Increment the depth33
if (traversal[i] == '-') {39
// Find the complete number as no.of digits can be > 140
int ind = findIndex(i, traversal);41
string str = traversal.substr(i, ind - i);42
TreeNode *node = new TreeNode(stoi(str));44
// Finding its appropriate parent, whose depth is one less than current46
while (!st.empty() && st.top().second != depth - 1) {50
// There is already left child for the parent51
if (st.top().first->left) {52
st.top().first->right = node;54
st.top().first->left = node;57
// Pushing that node and its depth into stack58
st.push({node, depth});