654-最大二叉树

654-最大二叉树

力扣654

https://leetcode-cn.com/problems/maximum-binary-tree/

当前节点任务:数组中找到最大的并构造节点,递归左右两边子数组构造出左右节点

由于默认函数没有必要的参数,所以得自己写一个,必要的参数如上面所说:左右子数组,所以需要start和end参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public TreeNode constructMaximumBinaryTree(int[] nums) {
return buildTree(nums, 0, nums.length - 1);
}

public TreeNode buildTree(int[] nums, int start, int end) {
if (start > end) return null;
int rootIdx = findMax(nums, start, end);
TreeNode root = new TreeNode(nums[rootIdx]);
root.left = buildTree(nums, start, rootIdx - 1);
root.right = buildTree(nums, rootIdx + 1, end);
return root;
}

public int findMax(int[] nums, int start, int end){
int maxIdx = start;
for (int i = start; i <= end; i++) {
if (nums[i] > nums[maxIdx]){
maxIdx = i;
}
}
return maxIdx;
}

其他树的题目点击这里

#
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×