[LeetCode] 654. Maximum Binary Tree

45 篇文章 0 订阅

原题链接:https://leetcode.com/problems/maximum-binary-tree/

1. 题目介绍

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

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

给出一个没有重复数字的整数数组。在这个数组的基础上,建立一个最大的树。
最大的树的定义是:
根节点是数组中最大的数字。
数组中最大的数字将数组一分为二,根节点的左子树是左半部分数组的最大的树,根节点的右子树是右半部分数组最大的树。

根据给出的数组构建一棵最大的树,并且返回这棵树的根节点。

2. 解题思路

本题是典型的递归求解问题。
对于每一步的计算,都是类似的。
设置一个递归函数,函数的功能就是从求解数组下标范围在start到end之间的最大的树。
首先,需要找到数组中最大的数在哪里,比如根节点的下标是index,找到后将根节点设为最大的数。
根节点的左子树,可以用递归函数求start到index-1范围内的最大的树,
根节点的右子树,可以用递归函数求index+1到end范围内的最大的树。

最后返回根节点即可。

实现代码

/**
 * 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 helper(0,nums.length-1,nums);
    }
    public TreeNode helper(int start, int end, int[] nums){
        if(start > end ){
            return null;
        }
        int max = 0;
        int max_index = start;
        for(int i = start ; i <=end ; i++){
            if(nums[i] > max){
                max = nums[i];
                max_index = i;
            }
        }
        
        TreeNode root = new TreeNode(nums[max_index]);
        root.left  = helper(start, max_index-1,nums);
        root.right = helper(max_index+1 , end, nums);
        return root;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值