原题链接
题目描述
给出每个节点的两个儿子节点,建立一棵二叉树(根节点为 1),如果是叶子节点,则输入0
。建好树后希望知道这棵二叉树的深度。二叉树的深度是指从根节点到叶子结点时,最多经过了几层。
最多有 10^6 个结点。
输入格式
第一行一个整数 n,表示节点数。
之后 n 行,第 i 行两个整数 l、r,分别表示节点 i 的左右子节点。若 l=0 则表示无左子节点,r=0同理。
输出格式
一个整数,表示最大节点深度。
输入输出样例
输入#1
7
2 7
3 6
4 5
0 0
0 0
0 0
0 0
输出#1
4
C++题解:
#include <bits/stdc++.h>
#define N 100005
#define ll long long
#define ull unsigned long long
#define il inline
#define rg register
using namespace std;
class Qin
{
inline ll read()
{
rg ll x(0);
rg bool w(1);
rg char ch(0);
while (!isdigit(ch))
{
if (ch == '-')
w = -1;
ch = getchar();
}
while (isdigit(ch))
{
x = (x << 3) + (x << 1) + (ch - '0');
ch = getchar();
}
return x * w; // 数字 * 正负号 = 实际数值
}
public:
il void operator>>(ll &x)
{
x = read();
}
il void operator>>(int &x)
{
x = read();
}
} qin;//快读
struct node
{
int lc, rc;
} a[1000005];
//储存一棵树,lc为左孩子节点在数组中的下标,rc同理
//deep(x) 表示以x号节点为根的树的深度
int deep(int x)
{
//如果节点编号为0,说明节点不存在,返回0
if (!x)
return 0;
//先递归求两个子树的深度
//根为x号节点的树的深度是其左右子树中深度大的子树的深度+1
return max(deep(a[x].lc), deep(a[x].rc)) + 1;
}
int main()
{
// cin.sync_with_stdio(false);
int n, l, r;
qin >> n;
for (int i = 1; i <= n; i++)
qin >> a[i].lc, qin >> a[i].rc;
//根节点为1,直接求深度并输出
cout << deep(1) << endl;
system("pause");
return 0;
}