当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
随机推荐
群辉查看硬盘存储占用的方式
Jingdong cloud released a new generation of distributed database StarDB 5.0
线上一次JVM FullGC搞得整晚都没睡,彻底崩溃
149. 直线上最多的点数-并查集做法
matplotlib画polygon, circle
LeetCode 622. 设计循环队列
入门3D建模基础教程详细分解
不要再用if-else
【统计机器学习】线性回归模型
力扣刷题之爬楼梯(7/30)
基于移动GIS的环保生态管理系统
Postgresql源码(64)查询执行——子模块Executor(2)执行前的数据结构和执行过程
Radondb mysql installation problems
Postgresql-xl global snapshot and GTM code walking (branch line)
SQL server 实现触发器备份表数据
Postgresql source code (64) Query execution - data structure and execution process before submodule Executor (2) execution
详解AST抽象语法树
The ecological environmental protection management system based on mobile GIS
【leetcode】剑指 Offer II 009. 乘积小于 K 的子数组(滑动窗口、双指针)
pg_memory_barrier_impl in Postgresql and C's volatile









