力扣刷题记录-654.最大二叉树

该博客介绍了如何使用递归方法解决654号LeetCode问题——构建最大二叉树。通过找到数组中最大值作为根节点,递归地在左右子区间构建子树,最终形成具有最大值特性的二叉树。示例和代码实现详细解释了整个过程。
摘要由CSDN通过智能技术生成

654.最大二叉树

一、题目描述

给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:

  1. 创建一个根节点,其值为 nums 中的最大值。
  2. 递归地在最大值 左边 的 子数组前缀上 构建左子树。
  3. 递归地在最大值 右边 的 子数组后缀上 构建右子树。

返回 nums 构建的 最大二叉树 。

示例:
Alt
提示:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • nums 中的所有整数 互不相同

二、解题思路

构造树一般采用的是前序遍历,因为先构造中间节点,然后递归构造左子树和右子树。

递归法

每次递归都找出这个区间段的最大值,区间左边作为左子树,右边作为右子树。

三、AC代码

递归法

class Solution {

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return constructMaxBinaryTree(nums, 0, nums.length);
    }

    TreeNode constructMaxBinaryTree(int[] nums, int begin, int end) {
        if (end - begin < 1) {
            return null;
        }
        if (end - begin == 1) {
            return new TreeNode(nums[begin]);
        }
        int maxIndex = begin;
        int maxValue = nums[begin];
        for (int i = begin+1; i < end; i++) {
            if (nums[i] > nums[maxIndex]) {
                maxIndex = i;
                maxValue = nums[i];
            }
        }
        TreeNode root = new TreeNode(maxValue);
        root.left = constructMaxBinaryTree(nums, begin, maxIndex);
        root.right = constructMaxBinaryTree(nums, maxIndex+1, end);
        return root;
    }

}

参考代码随想录:https://programmercarl.com/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值