1. question: 最大二叉树(中等)
给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:
创建一个根节点,其值为 nums 中的最大值。
递归地在最大值 左边 的 子数组前缀上 构建左子树。
递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums 构建的 最大二叉树 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-binary-tree
示例 1:

示例1
| 输入:nums = [3,2,1,6,0,5] 输出:[6,3,5,null,2,0,null,null,1] 解释:递归调用如下所示: - [3,2,1,6,0,5] 中的最大值是 6 ,左边部分是 [3,2,1] ,右边部分是 [0,5] 。 - [3,2,1] 中的最大值是 3 ,左边部分是 [] ,右边部分是 [2,1] 。 - 空数组,无子节点。 - [2,1] 中的最大值是 2 ,左边部分是 [] ,右边部分是 [1] 。 - 空数组,无子节点。 - 只有一个元素,所以子节点是一个值为 1 的节点。 - [0,5] 中的最大值是 5 ,左边部分是 [0] ,右边部分是 [] 。 - 只有一个元素,所以子节点是一个值为 0 的节点。 - 空数组,无子节点。
|
示例 2:

示例2
| 输入:nums = [3,2,1] 输出:[3,null,2,null,1]
|
提示:
| 1 <= nums.length <= 1000 0 <= nums[i] <= 1000 nums 中的所有整数 互不相同
|
2. answers
这道题的方法其实在题目中就已经描述清楚了:找最大值,创建根节点,划分左右子序列,递归遍历两个左右子序列。
具体做法和前两道题一样,采用索引下标传参。代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| public class Solution_0065 {
public static TreeNode recurConstructMBT(int[] nums, int left, int right) {
if(left == right) return new TreeNode(nums[left]);
int maxIndex = left; for (int i = left; i < right + 1; i++) { if(nums[i] > nums[maxIndex]) { maxIndex = i; } }
TreeNode root = new TreeNode(nums[maxIndex]);
if(maxIndex == left) root.left = null; else root.left = recurConstructMBT(nums, left, maxIndex - 1);
if(maxIndex == right) root.right = null; else root.right = recurConstructMBT(nums, maxIndex + 1, right);
return root; }
public static TreeNode constructMaximumBinaryTree(int[] nums) {
return recurConstructMBT(nums, 0, nums.length - 1); }
public static void main(String[] args) {
int[] nums = {3, 2, 1};
TreeNode root = constructMaximumBinaryTree(nums);
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(queue.size() > 0) { int length = queue.size();
while(length-- > 0) {
root = queue.poll(); System.out.print(root.val + "\t");
if(root.left != null) queue.offer(root.left); if(root.right != null) queue.offer(root.right); } } } }
|
3. 备注
参考力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台 (leetcode-cn.com),代码随想录 (programmercarl.com)。