洛谷 P4913 【深基16.例3】二叉树深度 (dfs/树)(入门级)
https://www.luogu.com.cn/problem/P4913
题目描述:
n 个结点的二叉树。给出每个结点的两个子结点编号,如果是叶子结点,则输入 0 0。
建好树这棵二叉树之后,请求出它的最大结点深度。
输入输出样例
输入 #1复制
7
2 7
3 6
4 5
0 0
0 0
0 0
0 0
输出 #1复制
4
看到二叉树,我们首先可以构建一个结构体来装下该节点的左右子节点
struct node { int left; int right; }tree[N];
接着dfs开始遍历深度
先到左子树,深度加一,如遇0(表示叶子节点),立即返回
右子树一样
dfs(tree[idx].left,depth+1); dfs(tree[idx].right,depth+1);
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=200200;
int n;
int ans=0;
struct node
{
int left;
int right;
}tree[N];
void dfs(int idx,int depth)
{
if(idx==0) return ;//到达了叶子节点,及时返回
ans=max(ans,depth);
dfs(tree[idx].left,depth+1);
dfs(tree[idx].right,depth+1);
}
int main()
{
cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>tree[i].left>>tree[i].right;
}
dfs(1,1);//从根节点开始遍历,这个地方的深度为1;
cout<<ans<<endl;
return 0;
}