源代码:
#include <iostream>
#include <cstdlib>
#include <stack>
using namespace std;
typedef struct BiTNode
{
char root;
struct BiTNode * lchild, * rchild;
}BiTNode, * BiTree;
//创建二叉树
void CreateBtree(BiTree * T)
{
char ch;
cout << "请输入字符:(输入#表示为空!)" << endl;
cin >> ch;
if (ch == '#')
{
*T = NULL;
}
else
{
*T = (BiTree)malloc(sizeof(BiTNode));
(*T)->root = ch;
CreateBtree(&(*T)->lchild);
CreateBtree(&(*T)->rchild);
}
}
void DepththFirstSearch(BiTree root)
{
if (!root)
{
return;
}
stack<BiTree> nodeStack;
nodeStack.push(root);
BiTree node;
while(!nodeStack.empty())
{
node = nodeStack.top();
nodeStack.pop();
cout << node->root << " ";
if(node->lchild)
{
nodeStack.push(node->lchild); //先将左子树入栈
}
if(node->rchild)
{
nodeStack.push(node->rchild); //再将右子树入栈
}
}
}
void releasetree(BiTree T)
{
if (T)
{
releasetree(T->lchild);
releasetree(T->rchild);
free(T);
T == NULL;
}
}
int main()
{
BiTree T;
CreateBtree(&T);
cout << "深度优先遍历:";
DepththFirstSearch(T);
cout << endl;
releasetree(T);
return 0;
}
运行结果截图: