I was trying to implement a BST in C++.This is a specific member function to perform in order traversal and return a vector with the elements of the tree.
Now the problem arises with the stack pop() function which I set to the current node.void value not ignored as it ought to be
I understand that the empty stack will return a void value after the preceding pop() call.But then what's the solution to this, cause it's required in this traversal algorithm to retrieve 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;
}
In C++ the method
std::stack::pop()
doesn't return the value removed from the stack. The reason is that there's no way in general to write such a function correctly from an exception-safety point of view.
You need to store the value first and then remove it with pop
... e.g.
Node *x = depthStack.top();
depthStack.pop();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With