Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BST: void value not ignored as it ought to be

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;

}
like image 301
devsaw Avatar asked Aug 03 '13 15:08

devsaw


1 Answers

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();
like image 99
6502 Avatar answered Oct 22 '22 02:10

6502