void preordertree(bitree t) //先序遍历 :递归
{ if (!t) return; //节点为空,退出 printf(t->data); //访问节点 if (t->lchild) preordertree(t->lchild); //递归遍历左子树 if (t->rchild) preordertree(t->rchild);//递归遍历右子树 } void preordertree(bitree t) //中序遍历 :递归 { if (!t) return; //节点为空,退出 if (t->lchild) preordertree(t->lchild); //递归遍历左子树 printf(t->data); //访问节点 if (t->rchild) preordertree(t->rchild); //递归遍历右子树 } void preordertree(bitree t) //后序遍历 :递归 { if (!t) return; //节点为空,退出 if (t->lchild) preordertree(t->lchild); //递归遍历左子树 if (t->rchild) preordertree(t->rchild); //递归遍历右子树 printf(t->data); //访问节点 } void inordertree(bitree t) //先序遍历 :非递归 { initstack(s); //创建栈 p = t; //将指针p指向树根t push(s, p); //根节点进栈 while (!stackempty(s)) //判断栈是否为空 { pop(s, p); //出栈 printf(p->data); //访问节点 if (p->rchild) push(s, p->rchild); //如果左孩子存在,则进栈 if (p->lchild) push(s, p->lchild); //如果右孩子存在,则进栈 } } void inordertree(bitree t) //中序遍历 :非递归 { initstack(s); //创建栈 p = t; //将指针p指向树根t while (p||!stackempty(s)) //判断栈是否为空 { if (p) { push(s, p); //节点存在,则进栈 p = p->lchild; //将指针指向左孩子 } else { pop(s, p); //节点不存在,则出栈 printf(p->data); //访问节点 p = p->rchild; //将指针指向右孩子 } } } void preordertree(bitree t) //后序遍历 :非递归 { initstack(s); //创建栈 p = t; //将指针p指向树根t r = NULL; //初始化标志 while (p || !IsEmpty(S)) { if (p) { push(s, p); //节点不为空,则进栈 p = p->lchild; //将指针指向左孩子 } else { gettop(s,p); //先不出栈,满足条件再出栈访问 if (p->right && p->right != r)//该节点存在右子树且右儿子没出栈,指向其右孩子 p = p->right; else //满足该结点没有右子树 或者 右儿子刚出栈,则出栈访问 { pop(s,p); printf(p->data); r = p; //记录最近出栈的结点 p = NULL; //该结点的左右子树都已出栈,所以要继续出栈,访问其父结点 } } }
原文:https://www.cnblogs.com/cheng111/p/14235070.html