读书人

关于BST后续遍历(非递归),该怎么处理

发布时间: 2013-12-19 00:33:34 作者: rapoo

关于BST后续遍历(非递归)

void post_order_stack(node*head)
{
if (head == nullptr)return;
node*cur = head;
node*q = nullptr;
stack<node*>st;
//st.push(cur);
while (!st.empty()||cur!=nullptr)
{
if (cur != nullptr)
{
st.push(cur);
cur = cur->left;
}
while (!st.empty())
{
cur = st.top();
st.pop();
if (cur->right == nullptr)
{
cout << cur->data << " ";
}
else
{
st.push(cur);
cur = cur->right;
break;
}
}
}
}

找不出来错误来,求高手。
[解决办法]
不用递归的话,需要手动添加一个标志,用于指示当前栈顶节点是否是第一次取到,下面是伪代码,仅供参考:

push root into stack;
while stack is not empty
{
p = peek stack
if p is leaf
print p;
pop stack;
else if the tag of p is fresh
if p has right child
push p->right into stack;
if p has left child
push p->left into stack;
mark the tag of p;
else
print t;
pop stack
}

读书人网 >C++

热点推荐