要创建的树
代码
#include <iostream>
#include <queue>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
};
Node *create(int data)
{
Node *newnode = new Node();
newnode->data = data;
newnode->left = newnode->right = nullptr;
return newnode;
}
void printTree_preorder(Node* root){//前序遍历 就是深度优先DFS
if(root == nullptr)return;
cout<<root->data<<" ";
printTree_preorder(root->left);
printTree_preorder(root->right);
}
void printTree_inorder(Node* root){//中序遍历
if(root == nullptr)return;
printTree_inorder(root->left);
cout<<root->data<<" ";
printTree_inorder(root->right);
}
void printTree_postorder(Node* root){//后序遍历
//左右节点都遍历完了,没有左右节点可遍历时,才轮到输出你
if(root == nullptr)return;
printTree_postorder(root->left);
printTree_postorder(root->right);
cout<<root->data<<" ";
}
//广度优先BFS
void BFS(Node* root){
queue<Node *> nodeQueue;
nodeQueue.push(root);//根节点入队
Node *node;//临时指针
while(!nodeQueue.empty()){//队列不为空
//既然队列不为空,那就必须要输出了
node = nodeQueue.front();//指针指向队列的第一个
nodeQueue.pop();//因为是队列,所以第一个,也就是对头,出队
cout<<node->data<<" ";//打印该节点
/*然后接下来的就是,如果有左右节点的话,就一起入队*/
if(node->left){
nodeQueue.push(node->left); //先将左子树入队
}
if(node->right){
nodeQueue.push(node->right); //再将右子树入队
}
}
}
int main()
{
// level 1
Node *root = create(1);
// level 2
root->left = create(2);
root->right = create(3);
// level 3
root->left->left = create(4);
root->left->right = create(5);
root->right->left = create(6);
root->right->right = create(7);
//level 4
root->left->right->left = create(9);
root->right->right->left = create(15);
printTree_preorder(root);
cout<<endl;
printTree_inorder(root);
cout<<endl;
printTree_postorder(root);
cout<<endl;
BFS(root);
cin.get();
return 0;
}
打印结果
1 2 4 5 9 3 6 7 15
4 2 9 5 1 6 3 15 7
4 9 5 2 6 15 7 3 1
1 2 3 4 5 6 7 9 15