试编写一个函数,返回一颗给定二叉树在中序遍历下的最后一个节点(分别用递归和非递归实现)
#include
#include
#define MAXSIZE 50
typedef char datatype;
typedef struct node
{
datatype data;
struct node *lchild,*rchild;
} bintnode,*bintree;
datatype a;//用来记录中序遍历最后一个节点
//用来存放非递归的根节点
typedef struct
{
bintree a[MAXSIZE];
int top;
} stack;
bintree inputbint()
{
datatype in;
bintree t;
if((in=getchar())=='#')
t=NULL;
else
{
t=(bintnode *)malloc(sizeof(bintnode));
t->data=in;
t->lchild=inputbint();
t->rchild=inputbint();
}
return t;
}
//前序遍历输出当前二叉树
void printbint(bintree root)
{
if(root==NULL)return;
else
{
printf("%c",root->data);
printbint(root->lchild);
printbint(root->rchild);
}
}
void findlast(bintree root)
{
if(root)
{
findlast(root->lchild);
a=root->data;
findlast(root->rchild);
}
}
datatype findlast2(bintree root)
{
datatype b;
stack s;
s.top=0;
do
{
if(root!=NULL)
{
s.a[s.top]=root;
s.top++;
root=root->lchild;
}
else
{
s.top--;
root=s.a[s.top];
if(root->rchild==NULL)
{
b=root->data;
}
root=root->rchild;
}
}
while(s.top!=0||root!=NULL);
return b;
}
int main()
{
bintree root;
datatype b;//为避免与递归混淆,为外声明b供非递归使用
printf("请输入二叉树,子节点为空请输#:\n");
root=inputbint();
printf("前序遍历输出二叉树为:");
printbint(root);
printf("\n");
findlast(root);//递归方式查找最后一个节点
printf("递归实现输出中序遍历最后一个节点为:");
printf("%c\n",a);
b=findlast2(root);
printf("非递归实现输出中序遍历最后一个节点为:");
printf("%c",b);
return 0;
}