Preorder recursive traversal method of array-shaped polytree with n-ary tree (n has the maximum value)

#include "stdio.h"
#include "stdlib.h"

#define new(Class) (Class*)malloc(sizeof(Class))  

typedef struct node Node;
struct node{
	Node *next[3];  
	char content;
};

Node* createTree(){
	Node* A = new(Node);
	Node* B = new(Node);
	Node* C = new(Node);
	Node* D = new(Node);
	Node * E = new (Node);
	Node* F = new(Node);
	Node* G = new(Node);
	Node* H = new(Node);
	Node* I = new(Node);
	
	A->content = 'A';
	B->content = 'B';
	C->content = 'C';
	D->content = 'D';
	E->content = 'E';
	F->content = 'F';
	G->content = 'G';
	H->content = 'H';
	I->content = 'I';
	
	A->next[0] = B;
	A->next[1] = C;
	A->next[2] = NULL;
	B->next[0] = D;
	B->next[1] = E;
	B->next[2] = F;
	C->next[0] = G;
	C->next[1] = H;
	C->next[2] = NULL;
	D->next[0] = NULL;
	D->next[1] = NULL;
	D->next[2] = NULL;
	E->next[0] = I;
	E->next[1] = NULL;
	E->next[2] = NULL;
	F->next[0] = NULL;
	F->next[1] = NULL;
	F->next[2] = NULL;
	G->next[0] = NULL;
	G->next[1] = NULL;
	G->next[2] = NULL;
	H->next[0] = NULL;
	H->next[1] = NULL;
	H->next[2] = NULL;
	I->next[0] = NULL;
	I->next[1] = NULL;
	I->next[2] = NULL;
	
	return A;
}

void readTree(Node* head){
	int i;
	Node* cursor = head;
	printf("%c\n", cursor->content);
	for(i = 0; i < 3; i++){
		if(cursor->next[i] != NULL){
			readTree(cursor->next[i]);
		}
	}
}


int main(){
	readTree(createTree());
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325519092&siteId=291194637