2013-08-03 161 views
4

我试图在C++中实现一个BST。这是一个特定的成员函数,用于执行遍历并返回带有树的元素的向量。 现在问题出现在我设置为当前节点的堆栈pop()函数中。
void value not ignored as it ought to beBST:void值不会被忽略,因为它应该是

据我所知,空栈将前面的pop()方法call.But那么什么是解决这个,因为它是需要在这个traversal algorithm检索从堆栈中的最后一个节点后,返回一个空值。

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; 

} 
+0

你做你的代码有空隙返回函数的“返回值”的东西。停止这样做是没有意义的。 – Mat

回答

7

在C++函数

std::stack::pop() 

不返回从堆栈中移除的值。原因在于,从异常安全的角度来看,通常没有办法正确编写这样的函数。

您需要先存储该值,然后使用pop ...例如将其删除。

Node *x = depthStack.top(); 
depthStack.pop(); 
相关问题