二叉树层次遍历的应用--改造二叉链表
来源:互联网 发布:程序员出路 编辑:程序博客网 时间:2024/05/16 17:18
一 问题描述
二 解题思路
利用二叉树的层次遍历,识别出不同层次,当某一层中的结点未从队列中出完时,那么刚出队列的结点的右相邻结点就是对头元素。
三 测试效果
四 代码
/* * to transform a binary tree*/#include <stdio.h>#include <stdlib.h>#include <math.h>#define ElemType int#define END -1#define MAX 100typedef 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 bintreeint thislevel; // the number of nodes in this levelint nextlevel; // the number of nodes in next levelint 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 queuenextlevel = 0; while(!QueueEmpty()) {p = DeQueue();thislevel--; // when a node is out from the queueif(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;}
五 编程体会
关键是运用队列和搞清层次遍历的时候每一层结点的情况。
- 二叉树层次遍历的应用--改造二叉链表
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历!!!
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 二叉树的层次遍历
- 【转载】IT旅途——程序员面试经验分享
- Brief Intro to Container Literals of Foundation Framework
- vc--基于mfc的上位机设计(一)
- Ubuntu13.04环境下载、编译Android源代码
- 记录下FMDB的简单使用
- 二叉树层次遍历的应用--改造二叉链表
- 深入剖析电感电流
- gcc和g++的区别
- 函数调用规则
- 安卓基础学习_Activity与Fragment
- HTTP抓包工具Fiddler
- 在MAC平台上 使用SDL 把SDL窗口加入子窗口中
- unique save
- 毕业两年多 写不出一篇像样的论文