#include "stdio.h" #include "stdlib.h" #define new(Class) (Class*)malloc(sizeof(Class)) typedef struct node Node; struct node{ Node *next; Node *nextLayer; //If there is an address, it means there is a next layer of linked list int num; }; //Get a 4-level multi-fork example tree Node* createTree(){ //statement Node* head; Node* layer2; Node * layer3_1; Node * layer3_2; //Construct the first layer (root) head = new(Node); head->num = 1; head->next = NULL; //construct the second layer layer2 = new(Node); layer2->num = 2; layer2->next = new(Node); layer2->next->num = 3; layer2->next->nextLayer = NULL; layer2->next->next = new(Node); layer2->next->next->num = 4; layer2->next->next->next = NULL; head->nextLayer = layer2; //The root node (the node whose num is 1) is connected to the second layer (the node whose num is 2) //Construct the third layer_first paragraph layer3_1 = new(Node); layer3_1->num = 5; layer3_1->nextLayer = NULL; layer3_1->next = new(Node); layer3_1->next->num = 6; layer3_1->next->nextLayer = NULL; layer3_1->next->next = NULL; layer2->nextLayer = layer3_1; //The second layer (node with num 2) connects to the third layer_first segment (node with num 5) //Construct the third layer_second segment layer3_2 = new(Node); layer3_2->num = 7; layer3_2->nextLayer = NULL; layer3_2->next = new(Node); layer3_2->next->num = 8; layer3_2->next->nextLayer = NULL; layer3_2->next->next = new(Node); layer3_2->next->next->num = 9; layer3_2->next->next->nextLayer = NULL; layer3_2->next->next->next = new(Node); layer3_2->next->next->next->num = 10; layer3_2->next->next->next->nextLayer = NULL; layer3_2->next->next->next->next = NULL; layer2->next->next->nextLayer = layer3_2; //The second layer (node with num 4) connects to the third layer_second segment (node with num 7) return head; } // preorder read void read(Node* head){ Node* cursor = head; /** Traverse the data of each node, When encountering a node with the next layer, directly call this function to read the next layer of the current node, After reading the next layer, continue to read the next node in the last loop. It is recommended to draw a recursive process to understand**/ while(cursor != NULL) { printf("%d\n", cursor->num); if(cursor->nextLayer != NULL) { read(cursor->nextLayer); } cursor = cursor->next; } } int main(){ read(createTree()); return 0; }
An example of a multi-fork tree
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325519100&siteId=291194637
Ranking