Files
python/TangDou/LuoGuBook/P4913.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

41 lines
1018 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
//树的结构体+存储数组
struct Node {
int left; // 左结点ID
int right;// 右结点ID
} t[N]; //i:当前结点ID
int n;
/**
测试用例:
7
2 7
3 6
4 5
0 0
0 0
0 0
0 0
*/
//求以x为根的树的高度,注意递归函数的定义,就是,它是干啥使的~,向定义上看齐,好理解
int dfs(int x) {
if (x == 0) return 0;//递归终止条件是遇到左结点或右结点标识的是0这个是和题意相关的每道题可能不一样。
//左结点报告它的高度右结点报告它的高度我只选择一个大的然后把我自己的1加上去再向上级领导汇报
return max(dfs(t[x].left), dfs(t[x].right)) + 1;
}
int main() {
//读入
cin >> n;
//创建二叉树 build
for (int i = 1; i <= n; i++) cin >> t[i].left >> t[i].right;
//求根开始的树的高度
cout << dfs(1);
return 0;
}