654. Maximum Binary Tree
Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
- The root is the maximum number in the array.
- The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
- The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
Example 1:
Input: [3,2,1,6,0,5] Output: return the tree root node representing the following tree: 6 / \ 3 5 \ / 2 0 \ 1
Note:
- The size of the given array will be in the range [1,1000].
题目含义:给了一堆不重复的数组,然后挑选一个最大的作为root,然后root左边的和右边的有分别按照这个方法进行构建。
1 private TreeNode createTreeNode(int[] nums,int begin,int end) 2 { 3 if (begin>end) return null; 4 int maxValue = Integer.MIN_VALUE; 5 int maxIndex = -1; 6 for (int i=begin;i<=end;i++) 7 { 8 if (nums[i]>maxValue) 9 { 10 maxIndex = i; 11 maxValue = nums[i]; 12 } 13 } 14 if (maxIndex<0) return null; 15 TreeNode node = new TreeNode(nums[maxIndex]); 16 node.left = createTreeNode(nums,begin,maxIndex-1); 17 node.right = createTreeNode(nums,maxIndex+1,end); 18 return node; 19 } 20 21 public TreeNode constructMaximumBinaryTree(int[] nums) { 22 if (nums.length == 0) return null; 23 return createTreeNode(nums,0,nums.length-1); 24 }
分类:
leetcode_tree
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!