洛谷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;  
}
 
相关推荐
行稳方能走远34 分钟前
Android C++ 学习笔记3
android·c++
练习时长一年40 分钟前
Leetcode热题100(跳跃游戏 II)
算法·leetcode·游戏
小白菜又菜6 小时前
Leetcode 3432. Count Partitions with Even Sum Difference
算法·leetcode
wuhen_n7 小时前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
sin_hielo7 小时前
leetcode 2483
数据结构·算法·leetcode
Xの哲學8 小时前
Linux多级时间轮:高精度定时器的艺术与科学
linux·服务器·网络·算法·边缘计算
大头流矢8 小时前
归并排序与计数排序详解
数据结构·算法·排序算法
阿闽ooo8 小时前
外观模式:从家庭电源控制看“简化接口“的设计智慧
c++·设计模式·外观模式
油泼辣子多加9 小时前
【信创】算法开发适配
人工智能·深度学习·算法·机器学习
一路往蓝-Anbo9 小时前
【第20期】延时的艺术:HAL_Delay vs vTaskDelay
c语言·数据结构·stm32·单片机·嵌入式硬件