p4913 二叉树的深度

这道题在二叉树中属于比较简单的题,而且题目还规定了1号节点为根节点,就不需要考虑那么多,本题根据输入的方式可知,我们用数组最好,在建树的时候,直接无脑输入,因为他输入的格式为顺序的。

做这道题的目的主要是为了练习一下建树。

void createTree(int n){
    if(n==0)return ;
    for(int i = 1; i <= n; i++){
        cin>>T[i].l>>T[i].r;
    }
}

下面是全部代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6+10;
struct node{
    int l,r;
}T[maxn];
int max1 = -1;
void createTree(int n){
    if(n==0)return ;
    for(int i = 1; i <= n; i++){
        cin>>T[i].l>>T[i].r;
    }
}
void dfs(int root,int depth){
    if(root==0) return ;
    max1 = max(max1,depth);
    dfs(T[root].l,depth+1);
    dfs(T[root].r,depth+1);
}
int main(){
    int n;
    cin>>n;
    createTree(n);
    dfs(1,1);
    cout<<max1<<endl;
    return 0;
}

 

posted @ 2022-04-22 20:00  没停过WA  阅读(34)  评论(0)    收藏  举报