题目链接:https://leetcode.cn/problems/maximum-binary-tree/
方法一 递归 - 数组拷贝
1 方法思想
2 代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if (nums == null || nums.length == 0) return null;
int[] max = findMax(nums); // max[0] 代表当前数组中最大值,max[1]代表对应的下标
TreeNode root = new TreeNode(max[0]);
if (max[1] > 0){
root.left = constructMaximumBinaryTree(Arrays.copyOfRange(nums, 0, max[1]));
}
if (nums.length > max[1] + 1){
root.right = constructMaximumBinaryTree(Arrays.copyOfRange(nums, max[1] + 1, nums.length));
}
return root;
}
public int[] findMax(int[] nums) {
int[] result = new int[2];
int tempNum = Integer.MIN_VALUE;
int tempIndex = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > tempNum){
tempNum = nums[i];
tempIndex = i;
}
}
result[0] = tempNum;
result[1] = tempIndex;
return result;
}
}
3 复杂度分析
时间复杂度:
空间复杂度:
4 涉及到知识点
5 总结
方法二 递归-传数组索引
1 方法思想
2 代码实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if (nums == null || nums.length == 0) return null;
return constructMaximum(nums, 0, nums.length);
}
public TreeNode constructMaximum(int[] nums, int startIndex, int endIndex) {
if (endIndex <= startIndex) return null;
int[] max = findMax(nums, startIndex, endIndex); // max[0] 代表当前数组中最大值,max[1]代表对应的下标
TreeNode root = new TreeNode(max[0]);
if (max[1] > startIndex){
root.left = constructMaximum(nums, startIndex, max[1]);
}
if (endIndex > max[1] + 1){
root.right = constructMaximum(nums, max[1] + 1, endIndex);
}
return root;
}
public int[] findMax(int[] nums, int startIndex, int endIndex) {
int[] result = new int[2];
int tempNum = Integer.MIN_VALUE;
int tempIndex = -1;
for (int i = startIndex; i < endIndex; i++) {
if (nums[i] > tempNum){
tempNum = nums[i];
tempIndex = i;
}
}
result[0] = tempNum;
result[1] = tempIndex;
return result;
}
}
3 复杂度分析
时间复杂度:
空间复杂度: