3015: 【普及/提高-】【P4913】二叉树深度

内存限制:128 MB 时间限制:1.000 S
评测方式:文本比较 命题人:
提交:4 解决:3

题目描述

有一个 lns="http://www.w3.org/1998/Math/MathML">(106) 个结点的二叉树。给出每个结点的两个子结点编号(均不超过 lns="http://www.w3.org/1998/Math/MathML">),建立一棵二叉树(根节点的编号为 lns="http://www.w3.org/1998/Math/MathML">1),如果是叶子结点,则输入 0 0

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

输入

第一行一个整数 lns="http://www.w3.org/1998/Math/MathML">,表示结点数。

之后 lns="http://www.w3.org/1998/Math/MathML"> 行,第 lns="http://www.w3.org/1998/Math/MathML"> 行两个整数 lns="http://www.w3.org/1998/Math/MathML">lns="http://www.w3.org/1998/Math/MathML">,分别表示结点 lns="http://www.w3.org/1998/Math/MathML"> 的左右子结点编号。若 lns="http://www.w3.org/1998/Math/MathML">=0 则表示无左子结点,lns="http://www.w3.org/1998/Math/MathML">=0 同理。

输出

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

样例输入 复制

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

样例输出 复制

4

提示

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 7;
struct Node {
	int left, right;
} t[MAXN];
int n;
void build(){
	for (int i = 1; i<=n; i++)
	    scanf("%d %d",&t[i].left, &t[i].right);
}
int dfs(int x) {
	if (!x) return 0;
	return max(dfs(t[x].left),dfs(t[x].right)) + 1;
}
int main(){
    cin >> n;
    build();
    cout << dfs(1);
	return 0;
}