二叉树实验(2)
二叉树各种遍历的另一种较为简单的写法
1.树结点结构体:
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
//TreeNode(int x):val(x),left(nullptr),right(nullptr){}
TreeNode(int x,TreeNode*l=nullptr,TreeNode*r=nullptr):val(x),left(l),right(r){}
};
2.BFS(队列)
void BFS(TreeNode *root){
queue<TreeNode*> Q;
Q.push(root);
while(!Q.empty()){
TreeNode* node=Q.front();
Q.pop();
cout<<"["<<node->val<<"]";
if(node->left){
Q.push(node->left);
}
if(node->right){
Q.push(node->right);
}
}
}
3.DFS(栈(递归),前中后(其实都是一个原理))
void DFS1(TreeNode *root){
if(!root)return;
cout<<"["<<root->val<<"]";
DFS1(root->left);
DFS1(root->right);
}
void DFS2(TreeNode *root){
if(!root)return;
DFS2(root->left);
cout<<"["<<root->val<<"]";
DFS2(root->right);
}
void DFS3(TreeNode *root){
if(!root)return;
DFS3(root->left);
DFS3(root->right);
cout<<"["<<root->val<<"]";
}
4.main函数
#include<iostream>
#include<queue>
using namespace std;
int main(){
//建树(不细说了,就是调用构造函数)
TreeNode n13(13),n12(12),n11(11),n10(10),n9(9),n8(8),
n7(7,nullptr,&n13),n6(6,nullptr,&n12),
5(5,&n10,&n11),n4(4,&n8,&n9),
n3(3,&n6,&n7),n2(2,&n4,&n5),n1(1,&n2,&n3);
cout<<"BFS:\n";
BFS(&n1);
cout<<"\nDFS1(前序):\n";
DFS1(&n1);
cout<<"\nDFS2(中序):\n";
DFS2(&n1);
cout<<"\nDFS3(后序):\n";
DFS3(&n1);
}
5.我们建的树是这个样子的
6.测试结果