leetcode 654
程序员文章站
2022-05-18 16:01:20
...
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return build(nums, 0, nums.length - 1);
}
TreeNode build(int[] nums, int low, int high){
//base case
if(low > high){
return null;
}
//找到数组最大值并给root赋值
int maxVal = Integer.MIN_VALUE;
int index = -1;
for (int i = low; i <= high; i++) {
if(nums[i] > maxVal){
maxVal = nums[i];
index = i;
}
}
//构造出树的根节点
TreeNode root = new TreeNode(maxVal);
root.left = build(nums, low, index - 1);
root.right = build(nums, index + 1, high);
return root;
}
}
下一篇: 背包问题
推荐阅读
-
[leetcode]不同路径三连击~
-
LeetCode——Department Highest Salary(花式使用IN以及GROUP BY)
-
LeetCode——Department Top Three Salaries(巧妙使用子查询)
-
LeetCode——Customers Who Never Order(灵活使用NOT IN以及IN)
-
leetcode 921. 使括号有效的最少添加(Python)
-
#leetcode刷题之路13-罗马数字转整数
-
#leetcode刷题之路48-旋转图像
-
#leetcode刷题之路46-全排列
-
LeetCode刷题第二天
-
#leetcode刷题之路45-跳跃游戏 II