当前位置:网站首页>剑指 Offer II 044. 二叉树每层的最大值-dfs法
剑指 Offer II 044. 二叉树每层的最大值-dfs法
2022-08-03 19:36:00 【Mr Gao】
剑指 Offer II 044. 二叉树每层的最大值
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
解释:
1
/
3 2
/ \ \
5 3 9
示例2:
输入: root = [1,2,3]
输出: [1,3]
解释:
1
/
2 3
示例3:
输入: root = [1]
输出: [1]
示例4:
输入: root = [1,null,2]
输出: [1,2]
解释:
1
2
示例5:
输入: root = []
输出: []
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
/** * Note: The returned array must be malloced, assume caller calls free(). */
int f(struct TreeNode* root){
if(root){
int a=f(root->left)+1;
int b=f(root->right)+1;
if(a>b){
return a;
}
else{
return b;
}
}
else{
return 0;
}
}
void f2(struct TreeNode* root,int h,int *a){
if(root){
f2(root->left,h+1,a);
f2(root->right,h+1,a);
if(root->val>a[h]){
a[h]=root->val;
}
}
}
int* largestValues(struct TreeNode* root, int* returnSize){
int h=f(root);
int *re=(int *)malloc(sizeof(int)*h);
* returnSize=h;
for(int i=0;i<h;i++){
re[i]=-2147483648;
}
f2(root,0,re);
return re;
}
边栏推荐
猜你喜欢
随机推荐
MySQL详细学习教程(建议收藏)
redis常用命令,HSET,XADD,XREAD,DEL等
622 设计循环队列——Leetcode天天刷【循环队列,数组模拟,双指针】(2022.8.2)
dpkg强制安装软件
从文本匹配到语义相关——新闻相似度计算的一般思路
按需视觉识别:愿景和初步方案
glide set gif start stop
Shell programming loop statement
JS 内置构造函数 扩展 prototype 继承 借用构造函数 组合式 原型式creat 寄生式 寄生组合式 call apply instanceof
高效目标检测:动态候选较大程度提升检测精度(附论文下载)
京东云发布新一代分布式数据库StarDB 5.0
2022年最新的Android面试大厂必考174题(附带详细答案)
relocation R_X86_64_PC32 against,/usr/bin/ld: final link failed: Bad value
flex布局
Postgresql源码(64)查询执行——子模块Executor(2)执行前的数据结构和执行过程
单调栈及其应用
LeetCode 622. Designing Circular Queues
Force is brushed buckle problem for the sum of two Numbers
虚拟机vmware设置nat模式上网
系统太多,多账号互通如何实现?









