二叉树的层次遍历

#include <queue>
#include <iostream>

using namespace std;

struct Node {
    int data;
    Node *left, *right;

    explicit Node(int data) {
        this->data = data;
        left = right = nullptr;
    }
};

void levelOrder(Node *root) {
    // Base Case
    if (!root)
        return;

    // Create an empty queue for level order tarversal
    queue<Node *> q;

    // Enqueue Root and initialize height
    q.push(root);

    while (!q.empty()) {
        // Print front of queue and remove it from queue
        root = q.front();
        q.pop();
        cout << root->data << " ";

        // Enqueue left child
        if (root->left)
            q.push(root->left);

        // Enqueue right child
        if (root->right)
            q.push(root->right);
    }
}

int main() {
    Node *root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->left->right = new Node(5);
    root->right->left = new Node(6);
    root->right->right = new Node(7);

    levelOrder(root);

    return 0;
}