树的广义表表示法C语言代码
时间: 2023-11-12 14:06:02 浏览: 89
以下是树的广义表表示法的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char data;
struct node *firstchild, *nextsibling;
} Node;
Node *createNode(char data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->firstchild = NULL;
newNode->nextsibling = NULL;
return newNode;
}
Node *createTree(char* str, int* index) {
Node *root = NULL;
Node *currentNode = NULL;
int i = *index;
while (str[i] != '\0') {
if (str[i] == '(') {
i++;
if (root == NULL) {
root = createNode(str[i]);
currentNode = root;
} else {
Node *newNode = createNode(str[i]);
if (currentNode->firstchild == NULL) {
currentNode->firstchild = newNode;
} else {
Node *temp = currentNode->firstchild;
while (temp->nextsibling != NULL) {
temp = temp->nextsibling;
}
temp->nextsibling = newNode;
}
currentNode = newNode;
}
} else if (str[i] == ')') {
currentNode = currentNode->nextsibling;
} else if (str[i] == ',') {
i++;
Node *newNode = createNode(str[i]);
Node *temp = currentNode->nextsibling;
while (temp->nextsibling != NULL) {
temp = temp->nextsibling;
}
temp->nextsibling = newNode;
currentNode = newNode;
}
i++;
}
return root;
}
void printTree(Node *root) {
if (root != NULL) {
printf("%c", root->data);
if (root->firstchild != NULL) {
printf("(");
printTree(root->firstchild);
printf(")");
}
if (root->nextsibling != NULL) {
printf(",");
printTree(root->nextsibling);
}
}
}
int main() {
char* str = "A(B(C,D),E(F(G(H))))";
int index = 0;
Node *root = createTree(str, &index);
printTree(root);
printf("\n");
return 0;
}
```
该代码实现了树的广义表表示法的创建和打印功能,其中createNode函数用于创建节点,createTree函数用于创建树,printTree函数用于打印树。在该示例代码中,字符串"A(B(C,D),E(F(G(H))))"表示的是下图所示的树:
```
A
/ \
B E
| |
C F
\ \
D G
|
H
```
阅读全文