【洛谷B3642】二叉树的遍历&二叉树深度

今天开始学习二叉树

先看第一道题

二叉树的遍历

题目描述

有一个 \(n(n \le 10^6)\) 个结点的二叉树。给出每个结点的两个子结点编号(均不超过 \(n\)),建立一棵二叉树(根节点的编号为 \(1\)),如果是叶子结点,则输入 0 0

建好树这棵二叉树之后,依次求出它的前序、中序、后序列遍历。

输入格式

第一行一个整数 \(n\),表示结点数。

之后 \(n\) 行,第 \(i\) 行两个整数 \(l\)\(r\),分别表示结点 \(i\) 的左右子结点编号。若 \(l=0\) 则表示无左子结点,\(r=0\) 同理。

输出格式

输出三行,每行 \(n\) 个数字,用空格隔开。

第一行是这个二叉树的前序遍历。

第二行是这个二叉树的中序遍历。

第三行是这个二叉树的后序遍历。

样例 #1

样例输入 #1

7
2 7
4 0
0 0
0 3
0 0
0 5
6 0

样例输出 #1

1 2 4 3 7 6 5
4 3 2 1 6 5 7
3 4 2 5 6 7 1

解法&&个人感想

我们都知道二叉树的三个遍历是这样
前序遍历:根左右
中序遍历:左根右
后序遍历:左右根
一开始一直想用邻接表建图做搞了好久 后面发现根本不需要
模版就是下面这样

#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n;
int l,r;
int leftchild[1000005],rightchild[1000005];
void firstorder(int x){
    if(x==0) return ;
    cout<<x<<' ';
    firstorder(leftchild[x]);
    firstorder(rightchild[x]);
}
void mediumorder(int x){
    if(x==0) return ;
    mediumorder(leftchild[x]);
    cout<<x<<' ';
    mediumorder(rightchild[x]);
}
void lastorder(int x){
    if(x==0) return ;
    lastorder(leftchild[x]);
    lastorder(rightchild[x]);
    cout<<x<<' ';
}
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d%d",&leftchild[i],&rightchild[i]);
    }
    firstorder(1);
    cout<<endl;
    mediumorder(1);
    cout<<endl;
    lastorder(1);
    system("pause");
    return 0;
}

  

我们再来看第二道题

【深基16.例3】二叉树深度

题目描述

有一个 \(n(n \le 10^6)\) 个结点的二叉树。给出每个结点的两个子结点编号(均不超过 \(n\)),建立一棵二叉树(根节点的编号为 \(1\)),如果是叶子结点,则输入 0 0

建好这棵二叉树之后,请求出它的深度。二叉树的深度是指从根节点到叶子结点时,最多经过了几层。

输入格式

第一行一个整数 \(n\),表示结点数。

之后 \(n\) 行,第 \(i\) 行两个整数 \(l\)\(r\),分别表示结点 \(i\) 的左右子结点编号。若 \(l=0\) 则表示无左子结点,\(r=0\) 同理。

输出格式

一个整数,表示最大结点深度。

样例 #1

样例输入 #1

7
2 7
3 6
4 5
0 0
0 0
0 0
0 0

样例输出 #1

4

解法&&个人感想

这道题就是DFS 裸的 很好理解
不说了

#include<bits/stdc++.h>
#define ll long long
using namespace std;
int ver[10000005],head[10000005],nex[10000005];
int d[1000005];
int vis[1000005];
int tot;
int n,x,y,ans;
void add(int x,int y){
    ver[++tot]=y;
    nex[tot]=head[x],head[x]=tot;
}
void dfs(int x){
    vis[x]=1;
    for(int i=head[x];i;i=nex[i]){
        int y=ver[i];
        if(vis[y]) continue;
        d[y]=d[x]+1;
        dfs(y);
    }
}
int main(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        scanf("%d%d",&x,&y);
        if(x!=0){
            add(i,x);add(x,i);
        }
        if(y!=0){
            add(i,y);add(y,i);
        }
    }
    d[1]=1;
    vis[1]=1;
    dfs(1);
    for(int i=1;i<=n;i++){
        ans=max(ans,d[i]);
    }
    printf("%d",ans);
    system("pause");
    return 0;
}

  

posted @ 2025-02-09 18:31  elainafan  阅读(166)  评论(0)    收藏  举报