您的位置:首页 > 其它

二叉树非递归三种遍历

2017-01-30 21:31 232 查看
非递归先序

void nicePreOrder(treeNode* s)//非递归先序
{
if (s == NULL)
{
return;
}
stack<treeNode*> st;

while (s != NULL || !st.empty())
{

while (s != NULL)
{
cout << s->data << " ";
st.push(s);
s = s->left;
}
treeNode* tmp = st.top();
st.pop();
s = tmp->right;
}

}


非递归中序

void niceInOrder(treeNode* s)//非递归中序
{
if (s == NULL)
{
return;
}
stack<treeNode*> st;

while (!st.empty() || s != NULL)
{
while (s != NULL)
{
st.push(s);
s = s->left;
}
treeNode* tmp = st.top();
st.pop();
cout << tmp->data << " ";
s = tmp->right;
}
}


非递归后序

void nicePastOrder(treeNode* s)//非递归后序遍历
//左右中
{
if (s == NULL)
{
return;
}
stack<treeNode*> st;
treeNode* tag = NULL;
while (s != NULL || !st.empty())
{
while (s != NULL)
{
st.push(s);
s = s->left;
}
treeNode* tmp = st.top();
st.pop();
if (tmp->right == NULL || tmp->right == tag)
{
cout << tmp->data << " ";
tag = tmp;
tmp = NULL;
}
else//发现该结点右边还有未访问的结点
{
st.push(tmp);
s = tmp->right;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: