领扣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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【精】LintCode领扣算法问题答案:1112. 寻找数据错误
下一篇:领扣LintCode算法问题答案-1104. 机器人能否返回原点

发表评论

最新留言

很好
[***.229.124.182]2024年04月27日 13时04分31秒