前进的道路不是一帆风顺的,要随时迎接挑战,敢于战胜困难!

坚持一下,找人聊聊天,释放一些压力!

 

把二元查找树转变成排序的双向链表

#include <iostream>
#include <time.h>

#define MAX_NUM 10

using namespace std;

struct BSTreeNode
{
 int m_nValue;
 BSTreeNode *m_pLeft;
 BSTreeNode *m_pRight;
};

int count=0;

void AddTree(BSTreeNode** T, int num)
{
 if (*T==NULL)
 {
  *T=(BSTreeNode*)malloc(sizeof(BSTreeNode));
  (*T)->m_nValue=num;
  (*T)->m_pLeft=NULL;
  (*T)->m_pRight=NULL;
 }
 else if ((*T)->m_nValue>num)
 {
  AddTree(&((*T)->m_pLeft), num);
 }
 else
 {
  AddTree(&((*T)->m_pRight), num);
 }
}

void MidTraversal(BSTreeNode* T)
{
 if(T!=NULL)
 {
  MidTraversal(T->m_pLeft);
  count++;
  if (count%5==0)
  {
   cout<<T->m_nValue<<endl;
  }
  else
  {
   cout<<T->m_nValue<<"\t";
  }

  MidTraversal(T->m_pRight);
 }
}

void ConvertNode(BSTreeNode* pNode, BSTreeNode** pLastNodeInList)
{
 if (pNode==NULL)
 {
  return;
 }

 BSTreeNode* pCurrent=pNode;

 if (pCurrent->m_pLeft!=NULL)
 {
  ConvertNode(pCurrent->m_pLeft, pLastNodeInList);
 }

 //Put the current node into the double-linked list
 //pLastNodeInList<--pCurrent
 //pLastNodeInList-->pCurrent
 pCurrent->m_pLeft=*pLastNodeInList;
 if (*pLastNodeInList!=NULL)
 {
  (*pLastNodeInList)->m_pRight=pCurrent;
 }

 *pLastNodeInList=pCurrent;

 if (pCurrent->m_pRight!=NULL)
 {
  ConvertNode(pCurrent->m_pRight, pLastNodeInList);
 }
}

void PrintList(BSTreeNode* L, int flag)
{
 BSTreeNode* p=L;
 while (p!=NULL)
 {
  count++;
  if (count%5==0)
  {
   cout<<p->m_nValue<<endl;
  }
  else
  {
   cout<<p->m_nValue<<"\t";
  }

  if (1==flag)
  {
   p=p->m_pRight;
  }
  else
  {
   p=p->m_pLeft;
  }
 }
}

BSTreeNode* ConvertSolution(BSTreeNode* pHeadOfTree)
{
 BSTreeNode* pLastNodeInList=NULL;
 ConvertNode(pHeadOfTree, &pLastNodeInList);

 cout<<"Last node is: "<<pLastNodeInList->m_nValue<<endl;
 pLastNodeInList->m_pRight=NULL;

 cout<<"Revert list is:\n";
 PrintList(pLastNodeInList, 2);

 BSTreeNode* pHeadOfList=pLastNodeInList;
 while(pHeadOfList&&pHeadOfList->m_pLeft)
  pHeadOfList=pHeadOfList->m_pLeft;
 cout<<"Normal list is: \n";
 PrintList(pHeadOfList, 1);

 return pHeadOfList;
}

int main()
{
 BSTreeNode* T=NULL;
 int num, i;

 srand((unsigned int)time(NULL));
 for (i=0; i<MAX_NUM; i++)
 {
  num=rand()%100+1;
  AddTree(&T, num);
 }

 cout<<"Mid reversal tree is:\n";
 MidTraversal(T);

 cout<<"\ndouble list is:\n";
 PrintList(ConvertSolution(T), 1);

 return 0;
}

posted on 2010-08-11 12:59  山径山精  阅读(513)  评论(0编辑  收藏  举报

导航