简体   繁体   中英

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;

}

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 ... eg

Node *x = depthStack.top();
depthStack.pop();

In C++ stack.pop() function doesn't return the value from the stack.

So ,first you store the values and then you pop it. In your case:


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.top();   //solution
                                 depthStack.pop();                             
                         list.push_back(cur->key);
                         cur = cur->right;
                                                      }

                                                                                                                                            }
return list;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM