洛谷P4913 【深基16.例3】二叉树深度(c嘎嘎)

题目链接P4913 【深基16.例3】二叉树深度 - 洛谷 | 计算机科学教育新生态

题目难度 :普及

解题思路:本题要求树的深度,即求左右子树高度的最大值,首先我们用结构体存树左右节点,然后分别递归地去左右子树的深度。

下面奉上代码部分:

cpp 复制代码
#include<bits/stdc++.h>  // 万能头文件
using namespace std;
typedef long long ll;
const int N = 1e6 + 10;      
int n;
int ans;
 
struct node
{
	int left,right;
	
}tree[N];

void dfs(int id,int deep)
{
	if(id == 0) return;//到达叶子节点
	ans = max(ans,deep);
	dfs(tree[id].left,deep + 1);//递归求左子树的深度 
	dfs(tree[id].right,deep + 1);//递归求右子树的深度 
}
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    
    cin >> n;
    for(int i=1; i<=n; i++)   cin >> tree[i].left >> tree[i].right;
    
    dfs(1,1);
    
    cout << ans << '\n';
    	

  
    return 0;  
}
 
相关推荐
是小胡嘛1 小时前
C++之Any类的模拟实现
linux·开发语言·c++
Want5954 小时前
C/C++跳动的爱心①
c语言·开发语言·c++
lingggggaaaa4 小时前
免杀对抗——C2远控篇&C&C++&DLL注入&过内存核晶&镂空新增&白加黑链&签名程序劫持
c语言·c++·学习·安全·网络安全·免杀对抗
phdsky4 小时前
【设计模式】建造者模式
c++·设计模式·建造者模式
H_-H4 小时前
关于const应用与const中的c++陷阱
c++
coderxiaohan4 小时前
【C++】多态
开发语言·c++
gfdhy5 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
百***06015 小时前
SpringMVC 请求参数接收
前端·javascript·算法
weixin_457760005 小时前
Python 数据结构
数据结构·windows·python
ceclar1235 小时前
C++范围操作(2)
开发语言·c++