人是棵会思考的芦苇,除了接受知识,我们要有时间,空间来自我思考!!!
《〈〈〈〈内容不断充实中〉〉〉〉》
1.把二元查找树转变成排序的双向链表(树)
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ |
6 14
/ | / |
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
首先我们定义的二元查找树 节点的数据结构如下:
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};
#include<stdio.h>
#include<stdlib.h>
typedef struct BSTreeNode{
int data;
struct BSTreeNode* leftchild;
struct BSTreeNode* rightchild;
}bstree,*tree;
#if 0
tree create_tree()
{
tree T=NULL;
int val;
T=(tree)malloc(sizeof(bstree));
printf("input value(0quit):");
scanf("%d",&val);//手动输入;
if(val!=0)
{
T->data=val;
T->leftchild=create_tree();
T->rightchild=create_tree();
}
else
{
T=NULL;
}
return T;
}
int dis_tree(tree T)
{
if(T==NULL)
{
printf("=");
return 0;
}
else
{
dis_tree(T->leftchild);
printf("%d",T->data);
dis_tree(T->rightchild);
return 0;
}
}
int main(int argc,char*argv[])
{
tree T1;
T1=create_tree();
dis_tree(T1);
destroy(T1);
return 1;
}
#endif
#if 1
tree pHead=NULL;
tree pdlist=NULL;
tree create_tree(int* ptr,int i);
void dis_Mtree(tree T);
void convertoDoubleLink(tree T);
void destroy(tree T);
tree create_tree(int* ptr,int i)
{
tree T=NULL;
T=(tree)malloc(sizeof(bstree));
if(ptr[i] != 0)
{
T->data=ptr[i];
T->leftchild=create_tree(ptr,i*2+1);
T->rightchild=create_tree(ptr,i*2+2);
}
else
{
T= NULL;
}
return T;
}
void dis_Mtree(tree T)
{
if(T!=NULL)
{
dis_Mtree(T->leftchild);
//printf("%d=",T->data);
convertoDoubleLink(T);
dis_Mtree(T->rightchild);
}
}
void convertoDoubleLink(tree T)
{
T->leftchild=pdlist;//plist濮嬬粓鎸囧悜T锛?
if(pdlist!=NULL)
{
pdlist->rightchild=T;
}
else
{
pHead=T;
}
pdlist=T;
printf("%d=",T->data);
}
void destroy(tree T)
{
tree T1;
if(T!=NULL)
{
T1=T;
destroy(T1->leftchild);
destroy(T1->rightchild);
printf("free node %d",T->data);
free(T1);
T1=NULL;
}
}
void destroylist(tree T)
{
tree T1;
while(T->leftchild!=NULL)
{
T=T->leftchild;
}
while(T!=NULL)
{
T1=T;
T=T->rightchild;
printf("free node %d",T1->data);
free(T1);
T1=NULL;
}
free(T);
T=NULL;
}
int main()
{
tree T1=NULL;
int arr[15]={10,6,14,4,8,12,16,0,0,0,0,0,0,0,0};
T1=create_tree(arr,0);
dis_Mtree(T1);
getchar();
//destroy(T1);
destroylist(T1);
return 1;
}
#endif