二叉树顺序存储先序遍历代码
时间: 2023-12-10 09:34:23 浏览: 78
以下是二叉树顺序存储先序遍历的代码:
```c
#define MAXSIZE 100
typedef struct TreeNode *BinTree;
struct TreeNode {
char Data;
int Left;
int Right;
} T1[MAXSIZE], T2[MAXSIZE];
int CreateTree(struct TreeNode T[]) {
int N, i, check[MAXSIZE];
char cl, cr;
scanf("%d\n", &N);
if (N) {
for (i = 0; i < N; i++) check[i] = 0;
for (i = 0; i < N; i++) {
scanf("%c %c %c\n", &T[i].Data, &cl, &cr);
if (cl != '-') {
T[i].Left = cl - '0';
check[T[i].Left] = 1;
} else {
T[i].Left = -1;
}
if (cr != '-') {
T[i].Right = cr - '0';
check[T[i].Right] = 1;
} else {
T[i].Right = -1;
}
}
for (i = 0; i < N; i++) {
if (!check[i]) break;
}
}
return i;
}
void PreOrderTraversal(BinTree BT) {
if (BT != -1) {
printf("%c ", T1[BT].Data);
PreOrderTraversal(T1[BT].Left);
PreOrderTraversal(T1[BT].Right);
}
}
int main() {
int Root;
Root = CreateTree(T1);
PreOrderTraversal(Root);
return 0;
}
```
阅读全文