一,构建节点(所有代码附在最后)
节点中包含当前节点的值和左孩子节点和右孩子节点
typedef struct node{
struct node* parent;
int i;
struct node* right_children;
struct node* left_children;
}NODE;
初始化节点:
NODE* new_node(NODE* parent){
NODE* temp = new NODE();
if(temp == NULL ){
cout<<"NODE error"<<endl;
}
temp->parent = parent;
temp->i=NULL;
temp->right_children=NULL;
temp->left_children=NULL;
return temp;
}
二,算法设计
由于二叉树存储数组时难以计算每个叶子节点的深度,故采用广度优先算法:
首先,将根节点压入队列
然后,在for循环中(循环次数为数组的长度),每次pop队列获得NODE节点(parent),设置完该节点的值后,初始化两个新的NODE节点(children)作为parent节点的左右孩子,并按照左孩子,右孩子的顺序压入到队列中。
最后,销毁队列。
①队列的初始化,pop,push,free代码:
QUEUE* new_queue(int length){ //新建队列
QUEUE *queue_tmp = new QUEUE();
if(queue_tmp == NULL){
cout<<"内存分配失败"<<endl;
}
queue_tmp->node_list = new NODE*[length];
if(queue_tmp->node_list == NULL){
cout<<"内存分配失败"<<endl;
}
queue_tmp->top = 0;
queue_tmp->max_length=length;
queue_tmp->bottom = 0;
return queue_tmp;
}
void push_queue(QUEUE *q,NODE *n){ // 压入队列
if((q->top+1)%(q->max_length+1) == q->bottom)
return;
q->node_list[q->top] = n;
q->top = (q->top+1)%(q->max_length+1);
}
NODE* pop_queue(QUEUE *q){ // 从队列中取出
if(q->bottom == q->top)
return NULL;
NODE *temp = q->node_list[q-