二叉树的先序/中序/后序(递归、非递归)+层序遍历

本文详细介绍了队列的基本操作,并通过实例展示了二叉树的各种遍历方法,包括递归与非递归实现。同时,文章还提供了完整的C++代码实现,帮助读者深入理解数据结构的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

queue 的基本操作举例如下:

queue入队,如例:q.push(x); 将x 接到队列的末端。
queue出队,如例:q.pop(); 弹出队列的第一个元素,注意,并不会返回被弹出元素的值。
访问queue队首元素,如例:q.front(),即最早被压入队列的元素。
访问queue队尾元素,如例:q.back(),即最后被压入队列的元素。
判断queue队列空,如例:q.empty(),当队列空时,返回true。
访问队列中的元素个数,如例:q.size()
#include<iostream>
#include<stack>
#include<queue>

using namespace std;

typedef struct TreeNode
{
    int data;
    struct TreeNode* lchild;
    struct TreeNode* rchild;
}TreeNode;


void pretravel(TreeNode* T)
{
    if (T != NULL)
    {
        cout << T->data << " ";
        pretravel(T->lchild);
        pretravel(T->rchild);
    }
}

void intravel(TreeNode* T)
{
    if (T != NULL)
    {
        intravel(T->lchild);
        cout << T->data<<" ";
        intravel(T->rchild);
    }
}

void posttravel(TreeNode* T)
{
    if (T != NULL)
    {
        posttravel(T->lchild);
        posttravel(T->rchild);
        cout << T->data << " ";
    }
}

/****************************************************/

void preOrdtravel(TreeNode* T) //先序非递归
{
    if (!T) 
        return;

    stack<TreeNode*> s;
    s.push(T);
    TreeNode* t;
    while (!s.empty())
    {
        t = s.top();   //出栈并打印
        cout << t->data << " ";
        s.pop();

        if (t->rchild)
            s.push(t->rchild);
        if (t->lchild)
            s.push(t->lchild);
    }

}


void inOrdTravel(TreeNode* T)  //中序非递归
{
    if (!T)
        return;

    TreeNode* cur = T;
    stack<TreeNode*> S;

    while (!S.empty() || cur != NULL)
    {
        if (cur != NULL)
        {
            S.push(cur);
            cur = cur->lchild;
        }
        else
        {
            //出栈并打印
            cout << S.top()->data << " ";
            cur = S.top()->rchild;
            S.pop();
        }
    }
}

void postOrdtravel(TreeNode *T)  //后序非递归
{

    if (T == NULL) return;

    TreeNode *p = T;
    stack<TreeNode *> S;
    TreeNode *last = T; //last=NULL(错误),必须是T(正确)
    S.push(p);
    while (!S.empty())
    {
        p = S.top(); //获取栈顶
        if ((p->lchild == NULL && p->rchild == NULL) || (p->rchild == NULL && last == p->lchild) || (last == p->rchild))
        {//打印并出栈,更新last
            cout << p->data << " ";
            last = p;
            S.pop();
        }
        else
        {
            if (p->rchild)
                S.push(p->rchild);
            if (p->lchild)
                S.push(p->lchild);
        }

    }
}

void levelTraver(TreeNode* T)  //层次遍历
{
    if (!T)
        return;

    queue<TreeNode*> Q;

    TreeNode* cur = T;

    Q.push(cur);
    while (!Q.empty())
    {
        cout << Q.front()->data << " ";
        cur = Q.front();
        Q.pop();
        if (cur->lchild)
            Q.push(cur->lchild);
        if (cur->rchild)
            Q.push(cur->rchild);
    }
}

int main()
{
    TreeNode* s1 = new TreeNode;
    TreeNode* s2 = new TreeNode;
    TreeNode* s3 = new TreeNode;
    TreeNode* s4 = new TreeNode;
    TreeNode* s5 = new TreeNode;
    TreeNode* s6 = new TreeNode;
    TreeNode* s7 = new TreeNode;

    s1->data = 1;
    s1->lchild = s2;
    s1->rchild = s5;

    s2->data = 2;
    s2->lchild = NULL;
    s2->rchild = s3;

    s3->data = 3;
    s3->lchild = s4;
    s3->rchild = NULL;

    s4->data = 4;
    s4->lchild = NULL;
    s4->rchild = NULL;

    s5->data = 5;
    s5->lchild = s6;
    s5->rchild = NULL;

    s6->data = 6;
    s6->lchild = NULL;
    s6->rchild = s7;

    s7->data = 7;
    s7->lchild = NULL;
    s7->rchild = NULL;

//遍历
    cout << "先序遍历"<<endl;
    pretravel(s1);       cout << endl;
    preOrdtravel(s1);    cout << endl;

    cout << "中序遍历" << endl;
    intravel(s1);        cout << endl;
    inOrdTravel(s1);     cout << endl;

    cout << "后序遍历" << endl;
    posttravel(s1);      cout << endl;
    postOrdtravel(s1);   cout << endl;

    cout << "层序遍历" << endl;
    levelTraver(s1);

    return 0;

}
当然,二叉树遍历有三种主要方式:遍历(根-左-右)、中遍历(左-根-右)和后序遍历(左-右-根)。非递归的层次遍历(也叫广度优遍历,从上到下、从左到右)通常使用队列来辅助实现。 这里分别给出这些遍历非递归算法代码: 1. 层序遍历(广度优遍历): ```c #include <stdio.h> #include <stdlib.h> #include <queue> struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; void levelOrder(struct TreeNode* root) { if (root == NULL) return; // 使用队列存储每一层的节点 queue<struct TreeNode*> q; q.push(root); while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; i++) { struct TreeNode* node = q.front(); q.pop(); printf("%d ", node->val); // 打印当前节点值 if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); } printf("\n"); // 换行表示新的一层 } } ``` 2. 遍历递归非递归两种方式,这里是非递归版本,使用栈): ```c void preorderNonRecursive(struct TreeNode* root) { if (root == NULL) return; stack<struct TreeNode*> s; s.push(root); while (!s.empty()) { struct TreeNode* node = s.top(); s.pop(); printf("%d ", node->val); // 打印当前节点值 if (node->right != NULL) s.push(node->right); if (node->left != NULL) s.push(node->left); } } ``` 3. 中遍历非递归,同样使用栈): ```c void inorderNonRecursive(struct TreeNode* root) { if (root == NULL) return; stack<struct TreeNode*> s; struct TreeNode* curr = root; while (curr != NULL || !s.empty()) { while (curr != NULL) { s.push(curr); curr = curr->left; } curr = s.top(); s.pop(); printf("%d ", curr->val); // 打印当前节点值 curr = curr->right; } } ``` 4. 后序遍历非递归,使用两个栈): ```c void postorderNonRecursive(struct TreeNode* root) { if (root == NULL) return; stack<struct TreeNode*> s1, s2; s1.push(root); while (!s1.empty()) { struct TreeNode* node = s1.top(); s1.pop(); s2.push(node); if (node->left != NULL) s1.push(node->left); if (node->right != NULL) s1.push(node->right); } while (!s2.empty()) { struct TreeNode* node = s2.top(); s2.pop(); printf("%d ", node->val); // 打印当前节点值 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值