654. 最大二叉树
难度中等
给定一个不重复的整数数组 nums
。 最大二叉树 可以用下面的算法从 nums
递归地构建:
- 创建一个根节点,其值为
nums
中的最大值。 - 递归地在最大值 左边 的 子数组前缀上 构建左子树。
- 递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 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;
}
}