二叉树的四种遍历方法(非指针)

按照顺序有前序遍历,中序遍历,后序遍历,层序遍历
判断根节点用一个父节点数组,没有父节点的即为根节点
可以搭配下面链接食用
https://ac.nowcoder.com/acm/contest/21763/D

点击查看代码
#include <bits/stdc++.h>

using namespace std;

const int N=5e5+10;

int n;

struct tree
{
    int l,r;//左孩子和右孩子
}a[N];

int fa[N];

void dfs1(int x)//二叉树的先序遍历
{
    if(x>=n+1||x==0)return;
    cout<<x<<" ";
    dfs1(a[x].l);
    dfs1(a[x].r);
}

void dfs2(int x)//二叉树的中序遍历
{
    if(x>=n+1||x==0)return;
    dfs2(a[x].l);
    cout<<x<<" ";
    dfs2(a[x].r);
}

void dfs3(int x)//二叉树的后序遍历
{
    if(x>=n+1||x==0)return;
    dfs3(a[x].l);
    dfs3(a[x].r);
    cout<<x<<" ";
}

void bfs(int x)//二叉树的层序遍历
{
    if (x >= n + 1 || x == 0) return;
    queue<int> q;
    q.push(x);
    while (!q.empty()) 
    {
        int tmp=q.front();
        q.pop();
        cout <<tmp<< " ";
        if (a[tmp].l<n+1&&a[tmp].l!=0) q.push(a[tmp].l);
        if (a[tmp].r<n+1&&a[tmp].r!=0) q.push(a[tmp].r);
    }
    
}

int main()
{
    cin>>n;
    int head=-1;
    for(int i=1,x,y,op;i<=n;i++)
    {
        cin>>x>>y>>op;
        if(op==0) a[y].l=x;
        else a[y].r=x;
        fa[x]=y;
    }
    
    for(int i=1;i<=n;i++)if(fa[i]==0)head=i;
    
    dfs1(head);
    cout<<'\n';
    dfs2(head);
    cout<<'\n';
    dfs3(head);
    cout<<'\n';
    bfs(head);
    return 0;
}
posted @ 2025-04-23 08:24  ha000star  阅读(14)  评论(0)    收藏  举报