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

/****************************** 
作者: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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值