谁能帮我讲解一下这个非递归法建立二叉树的思路
//建立二叉树,非递归算法,输入时按层次输入。以“$ "结束,以“! "表示孩子为空。 #include <stdio.h>
#include <stdlib.h>
typedef struct bnode{
char data;
struct bnode *lchild;
struct bnode *rchild;
}BinNode;
BinNode *root, *s, *q[100];
//非递归法建立二叉树
void Inittree()
{
int parent, children;
char ch;
parent=1;
children=0;
root=NULL;
printf( "\nPlease input the data: ");
scanf( "%d ",&ch); getchar();
while(ch!= '$ ')
{
s=NULL;
if (ch!= '! ')
{
s=malloc(sizeof(BinNode));
s-> rchild=NULL;
s-> lchild=NULL;
s-> data=ch;
}
children++;
q[children]=s;
if (children==1)
root=s;
else
{
if(s!=NULL&&q[parent]!=NULL)
{
if (children%2==0)
q[parent]-> lchild=s;
else
q[parent]-> rchild=s;
}
if(children%2==1)
parent++;
}
printf( "Please input the data: ");
scanf( "%c ",&ch); getchar();
}
}
void preorder(BinNode *root)
{
if(root!=NULL)
{
printf( "%4c ",root-> data);
preorder(root-> lchild);
preorder(root-> rchild);
}
}/*前序遍历*/
main()
{
Inittree();
preorder(root);
}