中序序列二叉树的非递归算法实现(调用栈的操作函数)

c语言 中序序列二叉树的非递归算法实现(调用栈的操作函数)

算法思想
冲当前的节点开始,如果当前的节点存在而且栈不为空,重复以下操作

  1. 如果当前的节点不为空,进栈并且遍历其左子树
  2. 读栈顶的节点,并输出,同时栈顶退栈,遍历其右子树
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
	int data;
	struct node *lchild,*rchild;
	
} node,*tree;
tree creat(){
	tree t;
	int ch;
	scanf("%d",&ch);
	if(ch==0)
	{
	t=NULL;}
	else{
		t=(tree)malloc(sizeof(node));
		t->data=ch;
		t->lchild=creat();
		t->rchild=creat();
	}
	return t;
}
int print(tree t)
{
	int top=0; 
tree s[50],p=t; 
do { 
	while(p!=NULL) 
	{
		if(top>49) return;
		top++;
		s[top]=p;
		p=p->lchild ;
	}
	if(top!=0)
	{
		p=s[top];
		printf(" %d",p->data);
		top=top-1;
		p=p->rchild;
	}
		
} while(p!=NULL||top!=0);
}


int main()
{   tree t;
     int sum,n=1;
	printf("请输入数据创建二叉树");
	t=creat();
   printf("中序序列为:");
	print(t);

	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43904021/article/details/88070409