BST: void value is not ignored, as it should be

I tried to implement BST in C ++. This is a special member function that executes when traversing an order and returns a vector with tree elements. Now the problem is with the pop () function of the stack that I installed for the current node.
void value not ignored as it ought to be

I understand that an empty stack will return an empty value after the previous call to pop (). But what is the solution to this problem, since in this workaround algorithm, you need to remove the last node from the stack.

 vector <int> BSTree::in_order_traversal() { vector <int> list; stack <Node *> depthStack; Node * cur = root; while ( !depthStack.empty() || cur != NULL ) { if (cur != NULL) { depthStack.push(cur); cur = cur->left; } else { cur = depthStack.pop(); // Heres the line list.push_back(cur->key); cur = cur->right; } } return list; } 
+5
source share
1 answer

In C ++ method

 std::stack::pop() 

does not return a value removed from the stack. The reason is that there is generally no way to correctly write such a function in terms of exception safety.

You need to save the value first and then delete it with pop ... for example

 Node *x = depthStack.top(); depthStack.pop(); 
+11
source

Source: https://habr.com/ru/post/1495113/


All Articles