首页 > 其他 > 详细

Leetcode之分治法专题-654. 最大二叉树(Maximum Binary Tree)

时间:2019-09-13 09:05:44      阅读:86      评论:0      收藏:0      [点我收藏+]

Leetcode之分治法专题-654. 最大二叉树(Maximum Binary Tree)


 

给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:

  1. 二叉树的根是数组中的最大元素。
  2. 左子树是通过数组中最大值左边部分构造出的最大二叉树。
  3. 右子树是通过数组中最大值右边部分构造出的最大二叉树。

通过给定的数组构建最大二叉树,并且输出这个树的根节点。

 

示例 :

输入:[3,2,1,6,0,5]
输出:返回下面这棵树的根节点:

      6
    /      3     5
    \    / 
     2  0   
               1

 

提示:

  1. 给定的数组的大小在 [1, 1000] 之间。

 

分别找l到r区间里的最大值,然后再构造其左右的子树就ok了。

/**
 * 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 buildTreeNode(nums,0,nums.length-1);
    }
    
    public TreeNode buildTreeNode(int[] nums,int l,int r){
        if(l>r){
            return null;
        }
        int index = -1;
        int max = Integer.MIN_VALUE;
        for(int i=l;i<=r;i++){
            if(nums[i]>max){
                max = nums[i];
                index = i;
            }
        }
        TreeNode res = new TreeNode(max);
        res.left = buildTreeNode(nums,l,index-1);
        res.right = buildTreeNode(nums,index+1,r);
        return res;
    }
}

 

Leetcode之分治法专题-654. 最大二叉树(Maximum Binary Tree)

原文:https://www.cnblogs.com/qinyuguan/p/11515743.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!