一 问题描述
二 解题思路
利用二叉树的层次遍历,识别出不同层次,当某一层中的结点未从队列中出完时,那么刚出队列的结点的右相邻结点就是对头元素。
三 测试效果
四 代码
/*
* to transform a binary tree
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define ElemType int
#define END -1
#define MAX 100
typedef struct BinNode {
ElemType data;
struct BinNode *left;
struct BinNode *right;
struct BinNode *sibling;
}BinNode;
typedef struct QueueNode {
struct BinNode *data;
struct QueueNode *next;
}QueueNode;
QueueNode *front, *rear;
void InQueue(struct BinNode *e) {
QueueNode *p = (QueueNode *)malloc(sizeof(QueueNode));
if(!p) {
perror("memory error!\n");
exit(EXIT_FAILURE);
}
p->data = e;
p->next = 0;
if(rear) rear->next = p;
rear = p;
if(!front) front = rear;
}
struct BinNode *DeQueue() {
if(!front) {
perror("the queue is empty!\n");
exit(EXIT_FAILURE);
}
struct BinNOde *p = front->data;
QueueNode *r = front;
front = front->next;
free(r);
if(!front) rear = NULL;
return p;
}
int QueueEmpty() {
return front == NULL?1:0;
}
struct BinNode *front_of_queue() {
return front->data;
}
void CreateBinTree(BinNode **t) {
ElemType e;
if(scanf("%d", &e) != 1) {
perror("input error!\n");
exit(EXIT_FAILURE);
}
if(e == END) return;
if(*t == NULL) {
*t = (BinNode *)malloc(sizeof(BinNode));
if(*t == NULL) {
perror("memory error!\n");
exit(EXIT_FAILURE);
}
(*t)->left = NULL;
(*t)->right = NULL;
(*t)->sibling = NULL;
(*t)->data = e;
}
CreateBinTree(&((*t)->left));
CreateBinTree(&((*t)->right));
}
void PreTranverse(BinNode *t) {
if(t) {
printf("%d\t", t->data);
if(t->sibling) {
printf("--%d\t", t->sibling->data);
}
PreTranverse(t->left);
PreTranverse(t->right);
}
}
void TransformBinTree(BinNode **t) {
if(!(*t)) return;
int level = 1; // the level of bintree
int thislevel; // the number of nodes in this level
int nextlevel; // the number of nodes in next level
int k = 0; // the number of leaves in bintree
int i, j;
BinNode *p;
InQueue(*t);
thislevel = 1; // when the root node is added into the queue
nextlevel = 0;
while(!QueueEmpty()) {
p = DeQueue();
thislevel--; // when a node is out from the queue
if(p->left) {
InQueue(p->left);
nextlevel++; // the children of current node
}
if(p->right) {
InQueue(p->right);
nextlevel++;
}
if(!thislevel) {
thislevel = nextlevel;
nextlevel = 0;
level++;
}
else p->sibling = front_of_queue();
}
}
int main() {
BinNode *root = NULL;
CreateBinTree(&root);
PreTranverse(root);
printf("\n");
TransformBinTree(&root);
PreTranverse(root);
printf("\n");
return 0;
}
五 编程体会
关键是运用队列和搞清层次遍历的时候每一层结点的情况。