C++ 实现二叉树的非递归遍历(栈实现)
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ 实现二叉树的非递归遍历(栈实现)相关的知识,希望对你有一定的参考价值。
void BinaryTree::PreOrder_Stack(BinTreeNode *cur) {
stack<BinTreeNode *>s;
while (cur || !s.empty())
if (cur) {
cout << cur->data << " ";
s.push(cur);
cur = cur->lchild;
} else {
cur = s.top();
s.pop();
cur = cur->rchild;
}
}
void BinaryTree::InOrder_Stack(BinTreeNode *cur) {
stack<BinTreeNode *>s;
while (cur || !s.empty())
if (cur) {
s.push(cur);
cur = cur->lchild;
} else {
cur = s.top();
s.pop();
cout << cur->data << " ";
cur = cur->rchild;
}
}
void BinaryTree::PostOrder_Stack(BinTreeNode *cur) {
stack<BinTreeNode *>s1;
stack<bool>s2;
bool flag;
while (cur || !s1.empty())
if (cur) {
flag = false;
s1.push(cur);
s2.push(flag);
cur = cur->lchild;
} else {
cur = s1.top();
flag = s2.top();
s1.pop();
s2.pop();
if (flag == false) {
flag = true;
s1.push(cur);
s2.push(flag);
cur = cur->rchild;
} else {
cout << cur->data << " ";
cur = NULL;
}
}
}
以上是关于C++ 实现二叉树的非递归遍历(栈实现)的主要内容,如果未能解决你的问题,请参考以下文章
每日一题如何进行二叉树的各种遍历的非递归算法实现?简要讲述。