转自 面试算法--二叉树DFS/BFS实现(C语言) - 简书
#include<iostream>
#include <queue>
#include<stack>
using namespace std;
struct Node
{
int nVal;
Node *pLeft;
Node *pRight;
Node(int val,Node* left=NULL,Node * right=NULL):nVal(val),pLeft(left),pRight(right){}; //构造
};
// 析构
void DestroyTree(Node *pRoot)
{
if (pRoot==NULL)
return;
Node* pLeft=pRoot->pLeft;
Node* pRight=pRoot->pRight;
delete pRoot;
pRoot =NULL;
DestroyTree(pLeft);
DestroyTree(pRight);
}
// 用queue实现的BFS
void BFS(Node *pRoot)
{
if (pRoot==NULL)
return;
queue<Node*> Q;
Q.push(pRoot);
while(!Q.empty())
{
Node *node = Q.front();
cout<<node->nVal<<"->";
if (node->pLeft!=NULL)
{
Q.push(node->pLeft);
}
if (node->pRight!=NULL)
{
Q.push(node->pRight);
}
Q.pop();
}
cout<<endl;
}
// DFS的递归实现
void DFS_Recursive(Node* pRoot)
{
if (pRoot==NULL)
return;
cout<<pRoot->nVal<<" ";
if (pRoot->pLeft!=NULL)
DFS_Recursive(pRoot->pLeft);
if (pRoot->pRight!=NULL)
DFS_Recursive(pRoot->pRight);
}
// DFS的迭代实现版本(stack)
void DFS_Iterative(Node* pRoot)
{
if (pRoot==NULL)
return;
stack<Node*> S;
S.push(pRoot);
while (!S.empty())
{
Node *node=S.top();
cout<<node->nVal<<",";
S.pop();
if (node->pRight!=NULL)
{
S.push(node->pRight);
}
if (node->pLeft!=NULL)
{
S.push(node->pLeft);
}
}
}
// 打印树的信息
void PrintTree(Node* pRoot)
{
if (pRoot==NULL)
return;
cout<<pRoot->nVal<<" ";
if (pRoot->pLeft!=NULL)
{
PrintTree(pRoot->pLeft);
}
if (pRoot->pRight!=NULL)
{
PrintTree(pRoot->pRight);
}
}
int main()
{
Node *node1=new Node(4);
Node *node2=new Node(5);
Node *node3=new Node(6);
Node* node4=new Node(2,node1,node2);
Node* node5=new Node(3,node3);
Node* node6=new Node(1,node4,node5);
Node* pRoot = node6;
//PrintTree(pRoot);
//DFS_Recursive(pRoot);
DFS_Iterative(pRoot);
DestroyTree(pRoot);
return 0;
}