我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第1篇文章,点击查看活动详情
654. 最大二叉树:
给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:
- 创建一个根节点,其值为
nums中的最大值。 - 递归地在最大值 左边 的 子数组前缀上 构建左子树。
- 递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums 构建的 最大二叉树 。
样例 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:
输入:
nums = [3,2,1]
输出:
[3,null,2,null,1]
提示:
1 <= nums.length <= 10000 <= nums[i] <= 1000nums中的所有整数 互不相同
分析
-
面对这道算法题目,二当家的陷入了沉思。
-
根据题意,一定要遍历数组的。
-
遍历一般就是考虑用循环或者递归。
-
本题要构建的二叉树结构,用递归非常直观。
题解
rust
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn construct_maximum_binary_tree(nums: Vec<i32>) -> Option<Rc<RefCell<TreeNode>>> {
if nums.len() == 0 {
return Option::None;
}
let mut max_i = 0;
for i in 0..nums.len() {
if nums[i] > nums[max_i] {
max_i = i;
}
}
Some(Rc::new(RefCell::new(TreeNode {
val: nums[max_i],
left: Self::construct_maximum_binary_tree(nums[..max_i].to_vec()),
right: Self::construct_maximum_binary_tree(nums[max_i + 1..].to_vec()),
})))
}
}
go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func constructMaximumBinaryTree(nums []int) *TreeNode {
if len(nums) == 0 {
return nil
}
maxIndex := 0
for i := 0; i < len(nums); i++ {
if nums[i] > nums[maxIndex] {
maxIndex = i
}
}
root := &TreeNode{
Val: nums[maxIndex],
Left: constructMaximumBinaryTree(nums[:maxIndex]),
Right: constructMaximumBinaryTree(nums[maxIndex+1:]),
}
return root
}
typescript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function constructMaximumBinaryTree(nums: number[]): TreeNode | null {
if (nums.length == 0) {
return null;
}
let maxIndex = 0;
for (let i = 0; i < nums.length; ++i) {
if (nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
var root = new TreeNode(nums[maxIndex]);
root.left = constructMaximumBinaryTree(nums.slice(0, maxIndex));
root.right = constructMaximumBinaryTree(nums.slice(maxIndex + 1));
return root;
};
c
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxIndex(int* nums, int numsSize){
int maxIndex = 0;
for (int i = 1; i < numsSize; ++i) {
if (nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize){
if (numsSize <= 0) {
return NULL;
}
int maxI = maxIndex(nums, numsSize);
struct TreeNode *root = malloc(sizeof(struct TreeNode));
root->val = nums[maxI];
root->left = constructMaximumBinaryTree(nums, maxI);
root->right = constructMaximumBinaryTree(nums + maxI + 1, numsSize - maxI - 1);
return root;
}
c++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int maxIndex(vector<int>& nums, int l, int r) {
int maxIndex = l;
for (int i = l + 1; i <= r; ++i) {
if (nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums, int l, int r) {
if (l > r) {
return nullptr;
}
int maxI = maxIndex(nums, l, r);
TreeNode* root = new TreeNode(nums[maxI]);
root->left = constructMaximumBinaryTree(nums, l, maxI - 1);
root->right = constructMaximumBinaryTree(nums, maxI + 1, r);
return root;
}
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return constructMaximumBinaryTree(nums, 0, nums.size() - 1);
}
};
java
/**
* 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) {
return constructMaximumBinaryTree(nums, 0, nums.length - 1);
}
private TreeNode constructMaximumBinaryTree(int[] nums, int l, int r) {
if (l > r) {
return null;
}
int maxIndex = maxIndex(nums, l, r);
TreeNode root = new TreeNode(nums[maxIndex]);
root.left = constructMaximumBinaryTree(nums, l, maxIndex - 1);
root.right = constructMaximumBinaryTree(nums, maxIndex + 1, r);
return root;
}
private int maxIndex(int[] nums, int l, int r) {
int maxIndex = l;
for (int i = l + 1; i <= r; ++i) {
if (nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
}
python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
if not nums:
return None
max_i = 0
for i in range(0, len(nums)):
if nums[i] > nums[max_i]:
max_i = i
root = TreeNode(nums[max_i])
root.left = self.constructMaximumBinaryTree(nums[:max_i])
root.right = self.constructMaximumBinaryTree(nums[max_i + 1:])
return root
原题传送门:https://leetcode.cn/problems/maximum-binary-tree/
非常感谢你阅读本文~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://juejin.cn/user/2771185768884824/posts 博客原创~