二叉树中序遍历非递归算法(c语言实现)

学习 时间:2026-03-30 16:14:26 阅读:1332
二叉树中序遍历非递归算法(c语言实现)要求用到栈的相关知识,包括栈的建立,什么什么的.写出全部的过程源代码.明早要交的作业,哪个给我写好了再加20分

最佳回答

迅速的帅哥

踏实的飞机

2026-03-30 16:14:26

#include "stdio。h"#include "stdlib。h"#include "string。h"#define null 0struct node {char data;struct node *lchild;struct node *rchild;};//先序,中序 建树struct node *create(char *pre,char *ord,int n){struct node * head;int ordsit;head=null;if(ndata=*pre;head->lchild=head->rchild=null;ordsit=0;while(ord[ordsit]!=*pre){ordsit++;}head->lchild=create(pre+1,ord,ordsit);head->rchild=create (pre+ordsit+1,ord+ordsit+1,n-ordsit-1);return head;}}//中序递归遍历void inorder(struct node *head){if(!head)return;else{inorder(head->lchild );printf("%c",head->data );inorder(head->rchild );}}//中序非递归遍历void inorder1(struct node *head){struct node *p;struct node *stack[20];int top=0;p=head;while(p||top!=0){while (p){stack[top++]=p;p=p->lchild ;}p=stack[--top];printf("%c ",p->data );p=p->rchild ;}}//主函数int main(){struct node * head;char pre[30],ord[30];int n;gets(pre);gets(ord);n=strlen(pre);head=create(pre,ord,n);inorder(head);printf("\n");inorder1(head);printf("\n");}//测试事例;几个月前自己编写,原版vc++ 6。0实验通过怎么样,老板,好激动给点面子给分!给分啊

最新回答共有2条回答

  • 兴奋的雪糕
    回复
    2026-03-30 16:14:26

    #include "stdio。h"#include "stdlib。h"#include "string。h"#define null 0struct node {char data;struct node *lchild;struct node *rchild;};//先序,中序 建树struct node *create(char *pre,char *ord,int n){struct node * head;int ordsit;head=null;if(ndata=*pre;head->lchild=head->rchild=null;ordsit=0;while(ord[ordsit]!=*pre){ordsit++;}head->lchild=create(pre+1,ord,ordsit);head->rchild=create (pre+ordsit+1,ord+ordsit+1,n-ordsit-1);return head;}}//中序递归遍历void inorder(struct node *head){if(!head)return;else{inorder(head->lchild );printf("%c",head->data );inorder(head->rchild );}}//中序非递归遍历void inorder1(struct node *head){struct node *p;struct node *stack[20];int top=0;p=head;while(p||top!=0){while (p){stack[top++]=p;p=p->lchild ;}p=stack[--top];printf("%c ",p->data );p=p->rchild ;}}//主函数int main(){struct node * head;char pre[30],ord[30];int n;gets(pre);gets(ord);n=strlen(pre);head=create(pre,ord,n);inorder(head);printf("\n");inorder1(head);printf("\n");}//测试事例;几个月前自己编写,原版vc++ 6。0实验通过怎么样,老板,好激动给点面子给分!给分啊

上一篇 求宫斗的形容词,像【莞尔一笑】这样的.

下一篇 有拆项法计算,8分之1+24分之1+48分之1+80分之1+120分之1=