c++树结构的遍历,前序遍历[等价于dfs],中序遍历,后序遍历,bfs

c++树结构的遍历,前序遍历[等价于dfs],中序遍历,后序遍历,bfs

要创建的树

在这里插入图片描述

代码

#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

视频教程

视频教程

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

踏过山河,踏过海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值