领扣LintCode算法问题答案-1106. 最大二叉树
发布日期:2021-06-30 17:09:52
浏览次数:2
分类:技术文章
本文共 1600 字,大约阅读时间需要 5 分钟。
领扣LintCode算法问题答案-1106. 最大二叉树
目录
1106. 最大二叉树
描述
给定一个没有重复元素的整数数组。根据此数组构建的最大二叉树定义如下:
- root是数组中的最大数字。
- 左子树是根据最大数字左侧的子数组构建的最大二叉树。
- 右子树是根据最大数字右侧的子数组构建的最大二叉树。
通过给定的数组构造最大二叉树并返回此树的根节点。
给定的数组的大小范围为 [1,1000]。
样例 1:
输入: {3,2,1,6,0,5}输出: 返回代表下面这棵树的根节点: 6 / \ 3 5 \ / 2 0 \ 1
样例 2:
输入: {1,2,3,4}输出: 返回代表下面这棵树的根节点: 4 / 3 / 2 / 1
题解
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */public class Solution { /** * @param nums: an array * @return: the maximum tree */ public TreeNode constructMaximumBinaryTree(int[] nums) { // Write your code here TreeNode root = constructMaximumBinaryTree(nums, 0, nums.length - 1); return root; } private TreeNode constructMaximumBinaryTree(int[] nums, int startIndex, int endIndex) { // Write your code here if (endIndex < startIndex) { return null; } int maxIndex = startIndex; for (int i = startIndex + 1; i <= endIndex; i++) { if (nums[i] > nums[maxIndex]) { maxIndex = i; } } TreeNode root = new TreeNode(nums[maxIndex]); root.left = constructMaximumBinaryTree(nums, startIndex, maxIndex - 1); root.right = constructMaximumBinaryTree(nums, maxIndex + 1, endIndex); return root; }}
鸣谢
非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。
欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。
转载地址:https://le-yi.blog.csdn.net/article/details/108841677 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
很好
[***.229.124.182]2024年04月27日 13时04分31秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
升级yosemite后java出错的解决
2019-04-30
开发人员与测试人员, 道不同也相谋
2019-04-30
Thirdparty之CrashRptProbe, 查询程序奔溃的利器
2019-04-30
基于VTK实现面绘制(SR)和体绘制(VR)的基本代码
2019-04-30
Visual Studio之RelWithDebInfo模式,“被忽视”的编译模式
2019-04-30
提示框的综合使用--UIAlertViewController
2019-04-30
最全的UIAlertController的使用
2019-04-30
CBPeripheralManager学习笔记
2019-04-30
CLLocationManager定位服务
2019-04-30
iOS 开发如何获取当前的应用版本号
2019-04-30
友盟统计的那些事
2019-04-30
3款流行的移动应用平台数据统计比较
2019-04-30
iOS 开发 实现 将16进制字符串转换成16进制数
2019-04-30
UILabel自适应高度和自动换行
2019-04-30
NSTimer的使用方法 --初始化、暂停、继续
2019-04-30
iOS开发支付宝 集成SDK注意事项
2019-04-30