首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

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

2013-12-19 
关于BST后续遍历(非递归)void post_order_stack(node*head){if (head nullptr)returnnode*cur head

关于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
}

热点排行