二叉树的三种常见遍历方式:先根遍历、中根遍历、后根遍历。
二叉树节点结构体如下:
struct node //根节点结构体
{
char name;
Node* parent;
Node* left_child;
Node* right_child;
};
定义三个遍历函数:
void pre_order(Node* Tree) //先根遍历
{
if(Tree) //如果不是空节点
{
cout<<Tree->name<<endl;//根,左,右
pre_order(Tree->left_child);
pre_order(Tree->right_child);
}
}
void in_order(Node* Tree) //中根遍历
{
if(Tree) //如果不是空节点
{
in_order(Tree->left_child);//左,根,右
cout<<Tree->name<<endl;
in_order(Tree->right_child);
}
}
void post_order(Node* Tree) //后根遍历
{
if(Tree) //如果不是空节点
{
post_order(Tree->left_child);//左,右,根
post_order(Tree->right_child);
cout<<Tree->name<<endl;
}
}
全部代码以及测试结果:
#include<iostream>
using namespace std;
struct node //根节点结构体
{
char name;
Node* parent;
Node* left_child;
Node* right_child;
};
void pre_order(Node* Tree) //先根遍历
{
if(Tree) //如果不是空节点
{
cout<<Tree->name<<endl; //根,左,右
pre_order(Tree->left_child);
pre_order(Tree->right_child);
}
}
void in_order(Node* Tree) //中根遍历
{
if(Tree) //如果不是空节点
{
in_order(Tree->left_child); //左,根,右
cout<<Tree->name<<endl;
in_order(Tree->right_child);
}
}
void post_order(Node* Tree) //后根遍历
{
if(Tree) //如果不是空节点
{
post_order(Tree->left_child); //左,右,根
post_order(Tree->right_child);
cout<<Tree->name<<endl;
}
}
int main()
{
Node node_A;
node_A.name = 'A';
node_A.parent = NULL;
Node node_B;
node_B.name = 'B';
node_F.parent = NULL;
node_F.left_child = NULL;
node_F.right_child = NULL;
Node node_C;
node_C.name = 'C';
node_C.parent = NULL;
node_C.left_child = NULL;
node_C.right_child = NULL;
Node node_D;
node_D.name = 'D';
node_D.parent = NULL;
node_D.left_child = NULL;
node_D.right_child = NULL;
Node node_E;
node_E.name = 'E';
node_E.parent = NULL;
node_E.left_child = NULL;
node_E.right_child = NULL;
Node node_F;
node_F.name = 'F';
node_F.parent = NULL;
node_F.left_child = NULL;
node_F.right_child = NULL;
node_A.parent = NULL;
node_A.left_child = &node_B;
node_A.right_child = &node_C;
node_B.parent = &node_A;
node_B.left_child = &node_D;
node_B.right_child = &node_E;
node_C.parent = &node_A;
node_C.left_child = NULL;
node_C.right_child = NULL;
node_D.parent = &node_B;
node_D.left_child = &node_F;
node_D.right_child = NULL;
node_E.parent = &node_B;
node_E.left_child = NULL;
node_E.right_child = NULL;
node_F.parent = &node_D;
node_F.left_child = NULL;
node_F.right_child = NULL;
pre_order(&node_A);
cout<<endl;
in_order(&node_A);
cout<<endl;
post_order(&node_A);
return 0;
}