Establish a binary tree linked list structure

Establish a binary tree linked list structure

topic

It is known that the non-empty binary tree adopts a sequential storage structure, and the data information of the nodes is stored in the array BT[0...MAXZize-1] in turn (if the element is 0, it means that it does not exist in the binary tree), please write an algorithm to generate the binary tree The linked list structure.

analysis

When looping to a certain point of BT[i], it is mainly to find the parent node of the node, and whose child node is the BT[i] node connected to is the main problem.

  • When calculating the parent node, j=(i-1)/2 ;
  • Is it the left child or the right child of j ?
    (1) If i-2*j-1==0 , it means that it is the left child of j .
    (2) If i-2*j-1!=0 means it is the right child of j

Code

Basic data type

The following code may have similar data types, so I won't repeat it later.

#define MAXSize 100
typedef struct bNode{    
	int data;    
	struct bNode *lchild,*rchild;   
 }BTNode,*BTREE;
 #define len sizeof(BTNode)

Core code

// 建立二叉树链表结构
BTREE CTREATEBLINK(int BT[],int n){    
	BTREE T=NULL,PRT[MAXSize];   
	 int j=0;    
	 PRT[j]=(BTREE) malloc(len);    
	 PRT[j]->data=BT[0];    
	 PRT[j]->rchild =NULL;   
	  PRT[j]->lchild= NULL ;    
	  T=PRT[j];    
	  for (int i = 1; i < n; i++)    {        
	  	if (BT[i]!=0)        {            
	  		PRT[i]=(BTREE) malloc(len);            
	  		PRT[i]->data=BT[i];           
	  	 	PRT[i]->rchild =NULL;           
	  	 	 PRT[i]->lchild= NULL ;            
	  	  	 j = (i-1)/2;            
	  	 	  if (i-2*j-1==0)            {                
	  	   		PRT[j]->lchild=PRT[i];            
	  	 	  }else            {               
	  	   		 PRT[j]->rchild=PRT[i];           
	  	  	  }                                 
	  	} // if   
	 }// for         
	return T;
}

Guess you like

Origin blog.csdn.net/honeylife/article/details/99968158