// 二叉树的二叉链表存储表示
typedef int ElemType;
typedef struct BinaryTreeNode {
ElemType data;
struct BinaryTreeNode *lchild;
struct BinaryTreeNode *rchild;
}BinaryTreeNode;
====================================================================================================================================
// 先序遍历
BinaryTreeNode * GoFarLeft(BinaryTreeNode *T, std::stack<BinaryTreeNode *> &st)
{
while (T->lchild != NULL)
{
printf("%2d", T->data);
st.push(T);
T = T->lchild;
}
return T;
}
void PreOrderTraverse(BinaryTreeNode *T, std::stack<BinaryTreeNode *> &st)
{
if (T != NULL)
{
BinaryTreeNode *t = GoFarLeft(T, st);
bool flag = true;
while (t)
{
if (flag)
{
printf("%2d", t->data);
}
if (t->rchild != NULL)
{
t = GoFarLeft(t->rchild, st);
flag = true;
}
else if (!st.empty())
{
t = st.top();
st.pop();
flag = false; //上溯至父节点,而父节点之前已经被打印出
}
else
{
t = NULL;
}
}
}
}
====================================================================================================================================
// 中序遍历
BinaryTreeNode * GoFarLeft(BinaryTreeNode *T, std::stack<BinaryTreeNode *> &st)
{
while (T->lchild != NULL)
{
st.push(T);
T = T->lchild;
}
return T;
}
void InOrderTraverse(BinaryTreeNode *T, std::stack<BinaryTreeNode *> &st)
{
if (T != NULL)
{
BinaryTreeNode *t = GoFarLeft(T, st);
while (t)
{
printf("%2d", t->data);
if (t->rchild != NULL)
{
t = GoFarLeft(t->rchild, st);
}
else if (!st.empty())
{
t = st.top();
st.pop();
}
else
{
t = NULL;
}
}
}
}
====================================================================================================================================
// 后序遍历
struct SNode {
BinaryTreeNode *p;
bool rvisited;
SNode(BinaryTreeNode *_p, bool _rvisited): p(_p), rvisited(_rvisited) {}
};
void GoFarLeft(BinaryTreeNode *T, std::stack<SNode> &st)
{
while (T != NULL)
{
st.push(SNode(T, false));
T = T->lchild;
}
}
void LastOrderTraverse(BinaryTreeNode *T, std::stack<SNode> &st)
{
if (T != NULL)
{
GoFarLeft(T, st);
while (!st.empty())
{
SNode t = st.top();
if (t.p->rchild == NULL || t.rvisited == true) // 结点t已‘最左’,如果右孩子为空或者右孩子已经访问,那么输出t
{
printf("%2d", t.p->data);
st.pop();
}
else
{
t.rvisited = true;
st.pop();
st.push(t);
GoFarLeft(t.p->rchild, st);
}
}
}
}