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