zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    [CTF]跳舞的小人
    [CTF]Rabbit加密
    [CTF]ROT5/13/18/47编码
    [CTF]URL编码
    [CTF]unicode编码
    [CTF]培根密码
    电机控制总结
    stm32f4定时器配置
    MOS管测量好坏测量方法
    四元数
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7715569.html
Copyright © 2011-2022 走看看