二叉树的遍历指按照一定的顺序访问二叉树的所有节点
访问方法一共四种:先序遍历,中序遍历,后续遍历,层序遍历
前三种遍历一般用DFS方法,层序遍历需要BFS方法
先、中、后序遍历,都是指的根节点的访问顺序
先序代码:1
2
3
4
5
6
7
8
9
10void preorder(node* root)
{
if(root==NULL)
{
return;
{
cout<<root->data;
preorder(root->left);
preorder(root->right)
}
中序代码:1
2
3
4
5
6
7
8
9
10void inorder(node* root)
{
if(root==NULL)
{
return;
}
inorder(root->left);
cout<<root->data;
inorder(root->right);
}
后续代码:1
2
3
4
5
6
7
8
9
10void postorder(node* root)
{
if(root==NULL)
{
return;
}
postorder(root->left);
postorder(root->right);
cout<<root->data;
}
层序遍历,是按照层次的顺序,访问节点,采用广度优先的访问方法结合队列实现操作,代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19void layerorder(node* root)
{
queue<node*> q;
q.push(root);
while(!q.empty())
{
node* now=q.front();
q.pop();
cout<<now->data;
if(now->left!=NULL)
{
q.push(now->left);
}
if(now->right!=NULL)
{
q.push(now->right);
}
}
}
