二叉树先序、中序遍历。
#include<cstdio>
#include<stack>
using namespace std;
typedef struct btree{
char data;
struct btree *ltree,*rtree;
}tree,*Tree;
//递归先序创建二叉树
void create(Tree &t)
{
char c;
scanf("%c",&c);
if(c==' ') t=NULL;
else{
t=new btree;//t=(Tree)malloc(sizeof(tree)),,,,t=(*btree)malloc(sizeof(btree))
t->data=c;
create(t->ltree);
create(t->rtree);
}
}
//非递归先序遍历
void PreOrder(Tree &t)
{
Tree p;
stack<Tree>s;
if(t){
s.push(t);
while(!s.empty()){
p=s.top();
s.pop();
while(p){
printf("%c\t",p->data);
if(p->rtree) s.push(p->rtree); //右子树非空进栈
p=p->ltree; //沿左子树往下走
}
}
}
}
//非递归中序遍历
void InOrder(Tree &t)
{
Tree p;
stack<Tree>s;
s.push(t);
while(!s.empty()){
while((p=s.top())&&p) s.push(p->ltree); //向左走到尽头,知直到没有左子树 MMMM
p=s.top();
s.pop();//最后一个节点的左子树为空,需要弹出
if(!s.empty()){
p=s.top();
printf("%c\t",p->data);//取出最后的左子树并访问
s.pop();
s.push(p->rtree);//将最后一个左子树的双亲的右子树入栈,下个循环开始遍历右子树的子树(上面MMM处)
}
}
}
int main()
{
Tree t;
create(t);
PreOrder(t);
printf("\n");
InOrder(t);
}
//输入:ABC DE G F (F后面有三个空格)

4万+

被折叠的 条评论
为什么被折叠?



