654. Maximum Binary Tree

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. 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:

  1. 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     }
复制代码

 

posted @   daniel456  阅读(115)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示