【发布时间】:2011-07-25 14:23:09
【问题描述】:
我正在尝试搜索二叉搜索树并将每个节点存储在堆栈中,因为我遍历树以便记住我的路径,以便我可以执行旋转。
这是我的代码:
template <typename T>
bool BST<T>::contains(const T& v, BSTNode *&t)
{
stack<BSTNode*> s;
BSTNode * g;
BSTNode * p;
if( t == NULL )
return false;
else if( v < t->element ){
s.push(t);
return contains( v, t->leftChild);
}
else if( v > t->element ){
s.push(t);
return contains( v, t->rightChild);
}
else
{
t->search_c += 1;
if(t->search_c > threshold) //we need to rotate
{//begin rotation
cout << s.size(); //outputs 1
}//end rotation
return true;
}
}
我认为问题在于每次调用函数时堆栈都会超出范围,因此当它找到我要查找的值时,它是唯一存储在堆栈中的东西。所以我的问题是,如何使堆栈包含我遍历的每个项目,而不仅仅是最后一个?
【问题讨论】:
-
你能让堆栈成为静态变量吗?还是将堆栈作为参数传递给函数?
-
你能把堆栈作为第三个参数传递吗?当然是参考;)
标签: c++ recursion binary-tree