本方法需要队列实现
设定
树的结点定义
将树节点定义为具有数据域和子结点域的结构体
typedef struct prototype_treeNode
{
Datatype data;
struct prototype_treeNode* children[N];
//N为子结点最大数量
} TreeNode, *Tree;
且子结点域中无子结点的位置用NULL
空指针填充
二叉树结点的定义
二叉树使用二叉链表表示
typedef struct prototype_biNode
{
Datatype data;
struct prototype_biNode *lchild, *rchild;
} BiNode, *BiTree;
队列定义
typedef struct prototype_queue
{
int front, rear;
void** Que;
} Queue;
Queue *createQueue() //创建队列
{
Queue *new_que = (Queue*)malloc(sizeof(Queue));
new_que->Que = (void**)malloc(100*sizeof(void*));
//100可以是任何数字
new_que->front = 0;
new_que->rear = 0;
return new_que;
}
bool isEmptyQueue(Queue *Q) //队为空返回true,不为空时返回false
{
return Q->front == Q->rear ? true : false;
}
void *deQueue(Queue *Q) //结点指针出队
{
if(isEmptyQueue(Q))
{
return NULL;
}
return Q->Que[Q->front++];
}
void enQueue(Queue *Q, void *node) //结点指针入队
{
Q->Que[Q->rear] = node;
Q->rear++;
}
实现代码
BiTree transform(TreeNode *root)
{
if (root == NULL)
{
return NULL;
}
BiTree retNode = (BiTree)malloc(sizeof(BiNode));
retNode->data = root->data;
retNode->rchild = NULL;
Queue *que = createQueue();
for (int i = 0; root->children[i] != NULL; i++)
{
enQueue(que, root->children[i]);
}
retNode->lchild = transform((TreeNode*)deQueue(que));
BiNode *ptr = retNode->lchild;
while (!isEmptyQueue(que))
{
ptr->rchild = transform((TreeNode*)deQueue(que));
ptr = ptr->rchild;
}
free(que);
return retNode;
}
附上一段示例代码
typedef char Datatype;
int main(void)
{
TreeNode *test = (TreeNode *)malloc(sizeof(TreeNode));
test->data = 'a';
test->children[0] = (TreeNode *)malloc(sizeof(TreeNode));
test->children[1] = (TreeNode *)malloc(sizeof(TreeNode));
test->children[2] = (TreeNode *)malloc(sizeof(TreeNode));
test->children[0]->data = 'b';
test->children[1]->data = 'c';
test->children[2]->data = 'd';
test->children[3] = NULL;
test->children[0]->children[0] = (TreeNode *)malloc(sizeof(TreeNode));
test->children[0]->children[1] = (TreeNode *)malloc(sizeof(TreeNode));
test->children[0]->children[0]->data = 'e';
test->children[0]->children[0]->children[0] = NULL;
test->children[0]->children[1]->data = 'f';
test->children[0]->children[1]->children[0] = NULL;
test->children[0]->children[2] = NULL;
test->children[1]->children[0] = (TreeNode *)malloc(sizeof(TreeNode));
test->children[1]->children[0]->data = 'g';
test->children[1]->children[0]->children[0] = NULL;
test->children[1]->children[1] = NULL;
test->children[2]->children[0] = (TreeNode *)malloc(sizeof(TreeNode));
test->children[2]->children[1] = (TreeNode *)malloc(sizeof(TreeNode));
test->children[2]->children[2] = (TreeNode *)malloc(sizeof(TreeNode));
test->children[2]->children[0]->data = 'h';
test->children[2]->children[1]->data = 'i';
test->children[2]->children[2]->data = 'j';
for (int i = 0; i <= 2; i++)
{
test->children[2]->children[i]->children[0] = NULL;
}
test->children[2]->children[3] = NULL;
BiTree shift = transform(test);
return 0;
}
即将如下的树1
转换成如下的二叉树2