树(1)把二叉查找树转换成有序的双向链表
2016-07-15 16:32
393 查看
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ /
6 14
/ / / /
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
基本思路:中序遍历
构造双向链表
c语言代码如下:
运行结果如下:
[root@localhost c++]# ./a.out
4
6
8
10
12
14
16
要求不能创建任何新的结点,只调整指针的指向。
10
/ /
6 14
/ / / /
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
基本思路:中序遍历
构造双向链表
c语言代码如下:
#include<stdio.h> #include<stdlib.h> typedef struct BinaryTree//结构体定义方式 { struct BinaryTree *pLeft;//c语言中不要忘记写这个struct struct BinaryTree *pRight; int value; }pNode,*NODE; pNode *pListIndex;//做双向链表索引 pNode *pHead;//双向链表头节点 pNode *convertToLink(pNode *pCurrent); pNode *create(int *a,int lo,int hi)//构造搜索二叉树 { if (lo > hi) return NULL ;//这里再次强调,没有等号,有的话就错了 int mid = (lo+hi)/2; pNode *pHead = (NODE)malloc(sizeof(pNode)); pHead->value = a[mid]; pHead->pLeft = create(a,lo,mid-1); pHead->pRight = create(a,mid+1,hi); return pHead; } void inOrder(pNode *pRoot)//中序遍历 { if (pRoot == NULL) return ; if (pRoot->pLeft != NULL) inOrder(pRoot->pLeft); convertToLink(pRoot); // printf("%d",pRoot->value); if (pRoot->pRight != NULL) inOrder(pRoot->pRight); } void convertToLink(pNode *pCurrent)//构造*双*向链表 { pCurrent->pLeft = pListIndex; if (pListIndex == NULL) pHead = pCurrent; else pListIndex->pRight = pCurrent; pListIndex = pCurrent; printf("%d\n",pCurrent->value); } int main() { int a[] = {4,6,8,10,12,14,16};//先排序 pNode *pRoot = create(a,0,6); inOrder(pRoot); return 0; }
运行结果如下:
[root@localhost c++]# ./a.out
4
6
8
10
12
14
16
相关文章推荐
- 如何组织构建多文件 C 语言程序(二)
- 如何写好 C main 函数
- Lua和C语言的交互详解
- C#实现获取系统目录并以Tree树叉显示的方法
- 关于C语言中参数的传值问题
- 简要对比C语言中三个用于退出进程的函数
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C语言中fchdir()函数和rewinddir()函数的使用详解
- C语言内存对齐实例详解
- C语言编程中统计输入的行数以及单词个数的方法
- C语言自动生成enum值和名字映射代码
- C语言练习题:自由落体的小球简单实例
- 使用C语言判断英文字符大小写的方法
- c语言实现的带通配符匹配算法
- C语言实现顺序表基本操作汇总
- C语言中进制知识汇总
- C语言判断一个数是否是2的幂次方或4的幂次方
- C语言中计算正弦的相关函数总结
- 使用C语言详解霍夫曼树数据结构