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.

一道简单的递归题,注意递归的过程和结束条件就好了

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return construct(nums,0,nums.length-1);
    }
     private TreeNode construct (int[] nums,int lo ,int hi){
         if(lo>hi)return null;
         int max = Integer.MIN_VALUE ;
         int pos= lo;
         for(int i =lo;i<=hi;i++)
         {
             if(max<nums[i])
             {
                 max=nums[i];
                 pos=i;
             }
         }
         TreeNode node = new TreeNode(max);
         node.left=construct(nums,lo,pos-1);
         node.right=construct(nums,pos+1,hi);
         return node;
     }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given an integer array with no duplicates. A maximum tree...
    九里阅读 417评论 3 0
  • Given an integer array with no duplicates. A maximum tree...
    Yo咯咯哒阅读 168评论 0 0
  • (一) 我曾不止一次地问过猴子,你为什么要随着那个叫做唐僧的人去西天取经。 猴子的回答很简单,他说累了。 我不知道...
    OnlyDog阅读 398评论 2 2
  • 八、真相大白 曹明霁、余破阵、云展、云念裳都已闻讯赶至。凌烟阁指着雪刀与舒九娘的尸身道,“舒掌门背后的伤口与那几位...
    德万托阿阅读 503评论 0 3
  • 当你情绪失控的时候,我不能责怪你,当你发怒的时候,我更要理解你。 我不能激怒,只能疏导。 我们都是A型...
    诉儿阅读 242评论 0 0