当前位置:网站首页>LeetCode 654. 最大二叉树
LeetCode 654. 最大二叉树
2022-07-22 09:17:00 【大白羊_Aries】
题目描述
解法:
这道题有点像二分法,关键就是对于每个根节点找到当前 nums 中的最大值和对应的索引,然后递归调用左右数组构造左右子树即可
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return build(nums, 0, nums.size() - 1);
}
TreeNode* build(vector<int>& nums, int low, int high){
if (low > high) return nullptr;
int index = -1, max_val = INT_MIN;
for (int i = low; i <= high; i++)
{
if (max_val < nums[i])
{
max_val = nums[i];
index = i;
}
}
TreeNode* root = new TreeNode(max_val);
root->left = build(nums, low, index - 1);
root->right = build(nums, index + 1, high);
return root;
}
};
边栏推荐
- NRF24L01无线模块设置发射接受模式方法
- 02.依赖导致原则 - Dependence Inversion Principle
- ECSHOP need to modify the folder and file of permission? The error directory cannot be written
- PTA 6-11 求自定类型元素序列的中位数 (25 分)
- 总结20220214
- Summary 20220119
- 1.雷点:mysql数据库转移到oracle,2.qt5.12.3 连接oracle 12c数据库
- LeetCode: 184. 部门工资最高的员工
- [SDIO] sd2.0 protocol analysis summary (I) -- Introduction to SD card basic probability
- amh多mysql版本共存?
猜你喜欢
App移动端测试【6】应用程序(apk)包管理与activity
App mobile terminal test [6] application program (APK) package management and activity
微信公众号网页授权----redirect_uri域名与后台配置不一致,错误码10003 错误
Interview experience of Android Internet manufacturers
[SDIO] sd2.0 protocol analysis summary (II) -- SD card identification & data transmission process
PTA基础题 7-23 币值转换 (20 分) (属实恶心)
01.开闭原则 Open-Closed Principle
模块TensorFlow中没有Session
【SDIO】SD2.0协议分析总结(二)-- SD卡识别&数据传输过程
Simple demonstration and prevention of CSRF attack in PHP development
随机推荐
【SDIO】SD2.0协议分析总结(一)-- SD卡基本概率介绍
No input file specified solution
Data Lake simple record
位与:一个数&1的结果
[Nordic] nrf52810 OTA upgrade (II) – how to use DFU
Go 语言学习:Go 语言之旅——练习题及参考答案
【TOOLS】TortoiseSVN如何设置比较工具为Beyond Compare 4
总结20220210
01.开闭原则 Open-Closed Principle
LeetCode: 596. 超过5名学生的课
[audio] analysis and summary of PCM audio data transmitted by I2S (I)
07. Composite/aggregate Reuse Principle (carp)
[STM32] STM32 SDIO SD card read / write test (II) -- SD_ Power on phase of init
总结20220208(kmp)
How can ECSHOP run super slow locally?
1.QTableWidget的closable,2.pro/build_pass、member,3.QString&&
【Audio】I2S传输PCM音频数据分析总结(一)
模块TensorFlow中没有Session
Go 并发模式:管道和取消
PAT乙级1020月饼(注意测点)