【数据结构】(十)二叉树的遍历
(一)说明:
中序遍历左中右,有左子树就一直访问下去,直到没有返回根,然后右子树,之后一层层向上回溯。
(二)前序遍历详解:
相关递归算法详解:
然后在返回函数时,依次将系统栈的结点依次弹出即可。
最后得到输出结果。
前序遍历代码:
//****************————《二叉树前序遍历》————****************//
#include <iostream>
using namespace std;
#include<string>
#define _CRT_SECURE_NO_WARNINGS
struct Binary
{
char ch;
struct Binary* lchild;
struct Binary* rchild;
};
void DiGui(struct Binary* N) //N可以代表任意结点
{
if (N == 0)
{
return;
}
else
{
cout << N->ch << " ";
DiGui(N->lchild);
DiGui(N->rchild);
}
}
void output()
{
Binary AN = { 'A',NULL,NULL };
Binary BN = { 'B',NULL,NULL };
Binary CN = { 'C',NULL,NULL };
Binary DN = { 'D',NULL,NULL };
Binary EN = { 'E',NULL,NULL };
Binary FN = { 'F',NULL,NULL };
Binary GN = { 'G',NULL,NULL };
Binary HN = { 'H',NULL,NULL };
AN.lchild = &BN;
AN.rchild = &CN;
BN.lchild = &DN;
DN.rchild = &HN;
CN.lchild = &EN;
CN.rchild = &FN;
FN.lchild = &GN;
DiGui(&AN); //递归遍历
}
int main()
{
output();
system("pause");
return 0;
}
中序遍历代码:
//****************————《二叉树中序遍历》————****************//
#include <iostream>
using namespace std;
#include<string>
#define _CRT_SECURE_NO_WARNINGS
struct Binary
{
char ch;
struct Binary* lchild;
struct Binary* rchild;
};
void DiGui(struct Binary* N) //N可以代表任意结点
{
if (N == 0)
{
return;
}
else
{
DiGui(N->lchild);
cout << N->ch << " ";
DiGui(N->rchild);
}
}
void output()
{
Binary AN = { 'A',NULL,NULL };
Binary BN = { 'B',NULL,NULL };
Binary CN = { 'C',NULL,NULL };
Binary DN = { 'D',NULL,NULL };
Binary EN = { 'E',NULL,NULL };
Binary FN = { 'F',NULL,NULL };
Binary GN = { 'G',NULL,NULL };
Binary HN = { 'H',NULL,NULL };
AN.lchild = &BN;
AN.rchild = &CN;
BN.lchild = &DN;
DN.rchild = &HN;
CN.lchild = &EN;
CN.rchild = &FN;
FN.lchild = &GN;
DiGui(&AN); //递归遍历
}
int main()
{
output();
system("pause");
return 0;
}
后序遍历:
//****************————《二叉树后序遍历》————****************//
#include <iostream>
using namespace std;
#include<string>
#define _CRT_SECURE_NO_WARNINGS
struct Binary
{
char ch;
struct Binary* lchild;
struct Binary* rchild;
};
void DiGui(struct Binary* N) //N可以代表任意结点
{
if (N == 0)
{
return;
}
else
{
DiGui(N->lchild);
DiGui(N->rchild);
cout << N->ch << " ";
}
}
void output()
{
Binary AN = { 'A',NULL,NULL };
Binary BN = { 'B',NULL,NULL };
Binary CN = { 'C',NULL,NULL };
Binary DN = { 'D',NULL,NULL };
Binary EN = { 'E',NULL,NULL };
Binary FN = { 'F',NULL,NULL };
Binary GN = { 'G',NULL,NULL };
Binary HN = { 'H',NULL,NULL };
AN.lchild = &BN;
AN.rchild = &CN;
BN.lchild = &DN;
DN.rchild = &HN;
CN.lchild = &EN;
CN.rchild = &FN;
FN.lchild = &GN;
DiGui(&AN); //递归遍历
}
int main()
{
output();
system("pause");
return 0;
}