/******************************
作者:cncoderalex
博客:http://blog.youkuaiyun.com/cncoderalex
*******************************/
#include"Test.h"
#include<iostream>
#include<queue>
using namespace std;
struct Node
{
int Data;
Node *pLeft;
Node *pRight;
};
Node *CreateTree(int Ary[], int nCount)
{
if (!Ary || nCount <= 0)
return NULL;
int index = 0;
Node *pRoot = new Node();
pRoot->pLeft = pRoot->pRight = NULL;
pRoot->Data = Ary[index++];
queue<Node *> que;
que.push(pRoot);
while (!que.empty())
{
Node *pParent = que.front();
que.pop();
if (index < nCount)
{
Node *pTemp = new Node();
pTemp->pLeft = pTemp->pRight = NULL;
pTemp->Data = Ary[index++];
pParent->pLeft = pTemp;
que.push(pTemp);
}
else
{
break;
}
if (index < nCount)
{
Node *pTemp = new Node();
pTemp->pLeft = pTemp->pRight = NULL;
pTemp->Data = Ary[index++];
pParent->pRight = pTemp;
que.push(pTemp);
}
else
{
break;
}
}
return pRoot;
}
void DestroyTree(Node *&pRoot)
{
if (!pRoot)
return;
DestroyTree(pRoot->pLeft);
DestroyTree(pRoot->pRight);
delete pRoot;
pRoot = NULL;
}
void BFS(Node *pRoot)
{
if (!pRoot)
return;
queue<Node *> que;
que.push(pRoot);
while (!que.empty())
{
Node *pTemp = que.front();
que.pop();
printf("%d ", pTemp->Data);
if (pTemp->pLeft)
{
que.push(pTemp->pLeft);
}
if (pTemp->pRight)
{
que.push(pTemp->pRight);
}
}
printf("\n");
}
void InOrderTraverse(Node *pRoot)
{
if (!pRoot)
return;
InOrderTraverse(pRoot->pLeft);
printf("%d ", pRoot->Data);
InOrderTraverse(pRoot->pRight);
}
void Convert2DList(Node *pRoot, Node *&pLeft, Node *&pRight)
{
if (!pRoot)
{
pLeft = pRoot = NULL;
return;
}
if (!pRoot->pLeft && !pRoot->pRight)
{
pLeft = pRight = pRoot;
return;
}
Node *pLeftRight = NULL;
Node *pRightLeft = NULL;
if (pRoot->pLeft)
{
Convert2DList(pRoot->pLeft, pLeft, pLeftRight);
pLeftRight->pRight = pRoot;
pRoot->pLeft = pLeftRight;
}
else
{
pLeft = pRoot;
pRoot->pLeft = NULL;
}
if (pRoot->pRight)
{
Convert2DList(pRoot->pRight, pRightLeft, pRight);
pRightLeft->pLeft = pRoot;
pRoot->pRight = pRightLeft;
}
else
{
pRight = pRoot;
pRoot->pRight = NULL;
}
}
void PrintDList(Node *pRoot)
{
if (!pRoot)
return;
printf("%d ", pRoot->Data);
while (pRoot->pRight)
{
pRoot = pRoot->pRight;
printf("%d ", pRoot->Data);
}
printf("\n");
}
void DestroyDList(Node *pRoot)
{
if (!pRoot)
return;
while (pRoot)
{
Node *pTemp = pRoot;
pRoot = pRoot->pRight;
delete pTemp;
}
}
int main()
{
printf("http://blog.youkuaiyun.com/cncoderalex");
printf("\n");
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
Node *pRoot = NULL;
int AryTree[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
pRoot = CreateTree(AryTree, sizeof(AryTree) / sizeof(int));
InOrderTraverse(pRoot);
printf("\n");
Node *pLeft = NULL, *pRight = NULL;
Convert2DList(pRoot, pLeft, pRight);
PrintDList(pLeft);
DestroyDList(pLeft);
system("pause");
return 0;
}