您的位置:首页 > 其它

二叉树 深度优先搜索 宽度优先搜索

2016-02-14 17:36 417 查看
/****************************** 
作者:cncoderalex 
博客:http://blog.csdn.net/cncoderalex 
*******************************/

#include<iostream>
#include<queue>
#include<stack>

using namespace std;

struct Node
{
int Data;
Node *pLeft;
Node *pRight;
};

Node *CreateNode(int Data)
{
Node *pNode = new Node();
pNode->Data = Data;
pNode->pLeft = NULL;
pNode->pRight = NULL;

return pNode;
}

Node *CreateTree(int Ary[], int Len)
{
if (Len <= 0)
return NULL;

Node *pRoot = CreateNode(Ary[0]);
std::queue<Node *> que;
que.push(pRoot);
int i = 0;
for (i = 2; i < Len; i += 2)
{
Node *pLeft = CreateNode(Ary[i - 1]);
Node *pRight = CreateNode(Ary[i]);

Node *pParent = que.front();
que.pop();

pParent->pLeft = pLeft;
pParent->pRight = pRight;

que.push(pLeft);
que.push(pRight);
}

if (i == Len)
{
Node *pLeft = CreateNode(Ary[i - 1]);

Node *pParent = que.front();
que.pop();

pParent->pLeft = pLeft;
}

return pRoot;
}

void DestroyTree(Node *&pRoot)
{
if (pRoot == NULL)
return;

if (pRoot->pLeft)
DestroyTree(pRoot->pLeft);

if (pRoot->pRight)
DestroyTree(pRoot->pRight);

delete pRoot;
pRoot = NULL;
}

void BFS(Node *pRoot)
{
if (pRoot == NULL)
return;

std::queue<Node *> que;
que.push(pRoot);
while (!que.empty())
{
Node *pNode = que.front();
que.pop();

if (pNode->pLeft)
que.push(pNode->pLeft);

if (pNode->pRight)
que.push(pNode->pRight);

printf("%d ", pNode->Data);
}

printf("\n");
}

void DFS(Node *pRoot)
{
if (pRoot == NULL)
return;

std::stack<Node *> sk;
Node *pNode = pRoot;
while (true)
{
while (pNode)
{
printf("%d ", pNode->Data);

sk.push(pNode);
pNode = pNode->pLeft;
}

bool bFound = false;
while (!sk.empty())
{
pNode = sk.top();
sk.pop();
if (pNode->pRight != NULL)
{
pNode = pNode->pRight;
bFound = true;
break;
}
}

if (!bFound)
break;
}

printf("\n");
}

void DFS_Recursion(Node *pRoot)
{
if (pRoot == NULL)
return;

printf("%d ", pRoot->Data);

if (pRoot->pLeft != NULL)
{
DFS_Recursion(pRoot->pLeft);
}

if (pRoot->pRight != NULL)
{
DFS_Recursion(pRoot->pRight);
}
}

int main()
{
printf("http://blog.csdn.net/cncoderalex");
printf("\n");

int Ary[] = { 5, 3, 2, 8, 10, 15, 12, 14, 18 };
Node *pRoot = CreateTree(Ary, sizeof(Ary) / sizeof(int));

BFS(pRoot);
DFS(pRoot);
DFS_Recursion(pRoot);

DestroyTree(pRoot);

system("pause");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: