创建二叉树的三种算法(递归和非递归)

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
创建二叉树的三种算法:
1、结构体定义:
struct node{
struct node *lchild;
struct node *rchild;
char ch;
};
2、算法部分
1)递归创建二叉树(无返回值法):
voidcreate(struct node **T)
{
charch;
std::cin>>ch;
top++;
}
}
else
{
std::cout<<"sorry,your enter is error"<<std::endl;
exit(0);
}
i++;
}ቤተ መጻሕፍቲ ባይዱ
return head;
}
搭配主函数即可使用:
int main(void)
{
struct node *head;
head = create();
return 0;
if( ch ==‘#’)
*T = NULL;
else
{
*T = (struct node *)malloc(sizeof(struct node));
*T->ch = ch;
create(&(*T)->lchild);
create(&(*T)->rchild);
}
}
搭配上主函数即可使用:
int main(void)
T->ch = ch;
T->lchild = create(T->lchild);
T->rchild = create(T->rchild);
return T;
}
return NULL;
}
搭配主函数即可使用:
int main(void)
{
struct node T,*head;
head = create(&T);
{
st=stack[--top];
while(stack[top-1]->rchild == st)
{
st=stack[--top];
}
}
else if((ch[i]=='#') && (flag==0))
{
flag = 1;
}
else if(ch[i]!='#')
{
tree = (struct node *)malloc(sizeof(struct node));
return 0;
}
3 )非递归创建树:
struct node *create()
{
char ch[20];
int i = 0, flag = 0 ,top = 0;
struct node *tree, *head, *stack[20], *st;
std::cin>>ch;
tree = (struct node *)malloc(sizeof(struct node));
{
structnode *tree;
create(&tree);
return 0;
}
2)递归创建二叉树(有返回值):
struct node *create(struct node *T)
{
char ch;
std::cin>>ch;
if( ch !=‘#’)
{
T = (struct node *)malloc(sizeof(struct node));
}
注:关于第一种递归方法使用指针的指针,如果要是看不明白,可以想象我们在最初学程序时的交换两个变量的值的做法。
head=tree;
tree->data = ch[i];
tree->lchild = NULL;
tree->rchild = NULL;
stack[top++] = tree;
int a = 0;
i++;
while(i<strlen(ch))
{
if((ch[i]=='#') && (flag==1))
tree->data = ch[i];
tree->lchild = NULL;
tree->rchild = NULL;
if(flag == 0)
{
stack[top-1]->lchild = tree;
stack[top] = tree;
top++;
}
if(flag == 1)
{
flag = 0;
stack[top-1]->rchild = tree;
相关文档
最新文档