zoukankan      html  css  js  c++  java
  • [leetcode] 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].

    分析:题目分析了一下,要求建立一个满足条件的树,使得根节点是数组里面最大的那个。

    建树类型的问题做的比较少,但是建树过程肯定就是找到根节点,然后不停的递归寻找左孩子和又孩子。

    在这个题目里,表述比较清晰,左孩子就是左面那个subarrray的最大值,右孩子就是右边那个subarray的最大值。所以比较清晰的知道是用递归的思路。

    代码如下:

     1 class Solution {
     2     public TreeNode constructMaximumBinaryTree(int[] nums) {
     3         if ( nums.length == 0 ) return null;
     4         return helper(0,nums.length-1,nums);
     5     }
     6 
     7     private TreeNode helper(int start, int end, int[] nums) {
     8         if ( start > end || start < 0 || end > nums.length - 1 ) return null;
     9         int max_index = 0;
    10         int max = Integer.MIN_VALUE;
    11         for ( int i = start ; i <= end ; i ++ ){
    12             if ( nums[i] > max ){
    13                 max = nums[i];
    14                 max_index = i;
    15             }
    16         }
    17         TreeNode root = new TreeNode(max);
    18         root.left = helper(start,max_index-1,nums);
    19         root.right = helper(max_index+1,end,nums);
    20         return root;
    21     }
    22 }

        AC:7ms,beats:100%。

        这里要注意递归结束条件,其实就是叶子节点的取值要返回null。

        拿到题目还是最好手写一些思路和代码,这样思路比较清晰。

  • 相关阅读:
    Java 中的定时任务(一)
    超实用 Git 使用方式介绍
    TCP 建立连接为什么要握 3 次手?
    OSI、TCP、IP、UDP 这些都是啥??
    Java 中线程安全问题
    PlantUML——3.Graphviz的安装
    PlantUML——2.中文乱码及解决
    PlantUML——1.Hello
    maven实战系列
    NGUI优化之Drawcall
  • 原文地址:https://www.cnblogs.com/boris1221/p/9812019.html
Copyright © 2011-2022 走看看