当前位置:网站首页>The sword refers to Offer II 044. The maximum value of each level of the binary tree-dfs method
The sword refers to Offer II 044. The maximum value of each level of the binary tree-dfs method
2022-08-03 19:42: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;
}
边栏推荐
- Postgresql source code (64) Query execution - data structure and execution process before submodule Executor (2) execution
- FreeRTOS中级篇
- 单调栈及其应用
- Interview Blitz: What Are Sticky Packs and Half Packs?How to deal with it?
- 1161 最大层内元素和——Leetcode天天刷【BFS】(2022.7.31)
- 【木马免杀】
- 线上一次JVM FullGC搞得整晚都没睡,彻底崩溃
- Postgresql source code (65) analysis of the working principle of the new snapshot system Globalvis
- 按需视觉识别:愿景和初步方案
- 基础软件与开发语言开源论坛| ChinaOSC
猜你喜欢
随机推荐
七夕之前,终于整出了带AI的美丽秘笈
awk语法-02-运算、数组、格式化输出
JMeter笔记5 |Badboy使用和录制
Solution for no navigation bar after Word is saved as PDF
Handler 源码解析
ECCV 2022 Oral | 满分论文!视频实例分割新SOTA: IDOL
机器学习中专业术语的个人理解与总结(纯小白)
虚拟机vmware设置nat模式上网
简易电子琴设计(c语言)
安装radondb mysql遇到问题
Climbing Stairs (7/30)
JWT详解
开源教育论坛| ChinaOSC
【STM32】标准库-自定义BootLoader
SQL server 实现触发器备份表数据
力扣刷题之移动零
「学习笔记」高斯消元
如何理解即时通讯开发移动网络的“弱”和“慢”
力扣刷题之爬楼梯(7/30)
国产虚拟化云宏CNware WinStack安装体验-5 开启集群HA