返回首页 C++ 模板

树的遍历模板

前序、中序、后序、层序——四种遍历方式与互相转换

树遍历 前序 中序 后序 层序 GESP6
#include <bits/stdc++.h>
using namespace std;

struct Node {
    int val;
    Node *left, *right;
    Node(int v) : val(v), left(nullptr), right(nullptr) {}
};

// 前序:根-左-右
void preorder(Node *root) {
    if (!root) return;
    cout << root->val << " ";
    preorder(root->left);
    preorder(root->right);
}

// 中序:左-根-右
void inorder(Node *root) {
    if (!root) return;
    inorder(root->left);
    cout << root->val << " ";
    inorder(root->right);
}

// 后序:左-右-根
void postorder(Node *root) {
    if (!root) return;
    postorder(root->left);
    postorder(root->right);
    cout << root->val << " ";
}

// 层序遍历(BFS)
void levelOrder(Node *root) {
    if (!root) return;
    queue<Node*> q;
    q.push(root);
    while (!q.empty()) {
        Node *cur = q.front(); q.pop();
        cout << cur->val << " ";
        if (cur->left) q.push(cur->left);
        if (cur->right) q.push(cur->right);
    }
}

int main() {
    //    1
    //   / \
    //  2   3
    // / \
    //4   5
    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);

    preorder(root);  cout << endl;  // 1 2 4 5 3
    inorder(root);   cout << endl;  // 4 2 5 1 3
    postorder(root); cout << endl;  // 4 5 2 3 1
    levelOrder(root);cout << endl;  // 1 2 3 4 5
    return 0;
}

📖 要点说明

⚠️ 常见错误