#include<cstdio> ///中序遍历
#include<cstdlib>
#include<stack>
using namespace std;
typedef struct Node{
int k;
Node *lchild,*rchild;
}Node,*Link;
Link p;int x;
void create(Link& T)
{
scanf("%d",&x);
if(x==-1) return ;
T=(Link)malloc(sizeof(Node));
T->lchild=T->rchild=NULL;
T->k=x;
create(T->lchild);
create(T->rchild);
}
void print(Link T)//递归 先序
{
if(!T) return;
printf("%d ",T->k);
print(T->lchild);
print(T->rchild);
}
// top pop push empty size
void stack_print(Link T)//栈 非递归中序
{
Link p;
stack<Link>s;
s.push(T);
while(!s.empty()){
while(p=s.top()) //向左走到尽头
s.push(p->lchild);
s.pop(); // 空指针退栈
if(!s.empty()){ //向右
p=s.top();
s.pop();
printf("%d ",p->k);
s.push(p->rchild);
}
}
}
void stack_print_2(Link T)//栈 非递归中序
{
Link p;
stack<Link>s;
p=T;
while(p||!s.empty()){
if(p){ //向左走到尽头
s.push(p);p=p->lchild;
}
else{ //向右
p=s.top();
s.pop();
printf("%d ",p->k);
p=p->rchild;
}
}
}
int main()
{
Link T=NULL;
create(T);
puts("递归先序遍历");
print(T);
puts("");
puts("非递归中序遍历");
stack_print(T);
puts("");
return 0;
}
/// 1 5 9 10 11 -1 -1 1 6 -1 -1 -1 -1 8 -1 -1 7 7 -1 -1 2 -1 -1
中序遍历
最新推荐文章于 2023-05-30 18:37:08 发布