递归法构造最大二叉树

654. 最大二叉树

难度中等

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

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

返回 nums 构建的最大二叉树

思路

本题可以使用递归法求解,类似于快排的解法

我们在当前的范围中找到最大值,然后不断递归其左侧与右侧范围,重复寻找当前范围的最大值并不断递归,直到该区间长度为0

package cn.edu.xjtu.carlWay.tree.maximumBinaryTree;

import cn.edu.xjtu.Util.TreeNode.TreeNode;

/**
 * 654. 最大二叉树
 * 给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:
 * <p>
 * 创建一个根节点,其值为 nums 中的最大值。
 * 递归地在最大值 左边 的 子数组前缀上 构建左子树。
 * 递归地在最大值 右边 的 子数组后缀上 构建右子树。
 * 返回 nums 构建的 最大二叉树 。
 * <p>
 * https://leetcode-cn.com/problems/maximum-binary-tree/
 */
public class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return helpConstruct(nums, 0, nums.length);
    }

    private TreeNode helpConstruct(int[] nums, int left, int right) {
        // 区间中无元素
        if (left == right) {
            return null;
        }
        // 区间剩余一个元素
        if (right - left == 1) {
            return new TreeNode(nums[left]);
        }
        int maxIdx = findMaxIdx(nums, left, right);// 寻找当前区间的最大值
        TreeNode root = new TreeNode(nums[maxIdx]);

        root.left = helpConstruct(nums, left, maxIdx);// 递归处理左侧
        root.right = helpConstruct(nums, maxIdx + 1, right);// 递归处理右侧
        return root;
    }

    /**
     * 寻找当前区间的最大值
     *
     * @param nums
     * @param left
     * @param right
     * @return
     */
    private int findMaxIdx(int[] nums, int left, int right) {
        int max = nums[left];
        int maxIdx = left;
        for (int i = left; i < right; i++) {
            if (nums[i] > max) {
                max = nums[i];
                maxIdx = i;
            }
        }
        return maxIdx;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hydrion-Qlz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值