#include<stdio.h> typedef struct node{ int data; struct node *lchild,*rchild; }Tree; Tree* CreatTree(int in[],int post[],int n) { if(n==0) return NULL; int i; Tree *tree=(Tree*)malloc(sizeof(Tree)); tree->data=post[n-1]; for(i=0;i<n;i++) if(post[n-1]==in[i]) break; tree->lchild=CreatTree(in,post,i); tree->rchild=CreatTree(in+i+1,post+i,n-i-1); return tree; } void CountTree(Tree* tree) { if(tree!=NULL) { printf(" %d",tree->data); CountTree(tree->lchild); CountTree(tree->rchild); } } int main() { int n,i,j; int post[100001],in[100001]; scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&post[i]); for(i=0;i<n;i++) scanf("%d",&in[i]); Tree* tree=CreatTree(in,post,n); printf("Preorder:"); CountTree(tree); }
时间: 2024-04-28 21:19:01 浏览: 8
这是一段 C 语言代码,实现了根据中序遍历和后序遍历构建二叉树,并输出先序遍历结果。具体来说,代码中定义了一个结构体 `Tree`,表示二叉树的节点,包含节点的值 `data`,以及左右子树的指针 `lchild` 和 `rchild`。函数 `CreatTree` 是根据中序遍历数组 `in[]` 和后序遍历数组 `post[]` 构建二叉树的函数,通过递归实现。函数 `CountTree` 是输出二叉树先序遍历结果的函数,同样也是通过递归实现。在 `main` 函数中,先读入节点个数 `n`,以及中序遍历和后序遍历数组,然后调用 `CreatTree` 函数构建二叉树,并调用 `CountTree` 函数输出先序遍历结果。
相关问题
#include <stdio.h> #include <stdlib.h> typedef int ElemType; typedef struct LNode { ElemType da
`#include <stdio.h>`和`#include <stdlib.h>`是C语言中的两个头文件。`<stdio.h>`是标准输入输出头文件,提供了一些用于输入输出的函数和宏定义。`<stdlib.h>`是标准库头文件,提供了一些常用的函数和宏定义,如内存分配、随机数生成等。
在你的代码中,`typedef int ElemType;`定义了一个类型别名,将`int`类型命名为`ElemType`。
`typedef struct LNode`定义了一个结构体类型`LNode`,结构体是一种自定义的数据类型,可以包含多个不同类型的成员变量。在这里,`LNode`结构体中的成员变量还没有完整定义,因此代码截断了。
补全#include<stdio.h> #include<malloc.h> #define MaxSize 50 typedef int ElemType; typedef struct { Elem
#include<stdio.h>
#include<malloc.h>
#define MaxSize 50
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int length;
}SqList;
这段代码是一个C语言的头文件补全,包含了stdio.h和malloc.h两个头文件,并定义了一个常量MaxSize为50。同时,定义了一个类型别名ElemType为int,并声明了一个结构体SqList,其中包含了一个数组data和一个整型变量length。