我思故我在——数据结构题(来自v_JULY_v,作者July)

 

人是棵会思考的芦苇,除了接受知识,我们要有时间,空间来自我思考!!!

《〈〈〈〈内容不断充实中〉〉〉〉》

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

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值