力扣654:最大二叉树

力扣654:最大二叉树

题目

给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:

  1. 创建一个根节点,其值为 nums 中的最大值。
  2. 递归地在最大值 左边 的 子数组前缀上 构建左子树。
  3. 递归地在最大值 右边 的 子数组后缀上 构建右子树。

返回 nums 构建的 最大二叉树 。

思路

题目已经把思路给我们了,我们只需要实现对应的函数即可。

代码

cpp 复制代码
/**
 * 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 {
public:
    TreeNode* recursion(vector<int>& nums, int left, int right) {
        if (left > right) {
            return nullptr;
        }
        int maxloca = left;
        for (int i = left + 1; i <= right; i++) {
            if (nums[maxloca] < nums[i]) {
                maxloca = i;
            }
        }
        TreeNode* root = new TreeNode(nums[maxloca]);
        root->left = recursion(nums, left, maxloca - 1);
        root->right = recursion(nums, maxloca + 1, right);
        return root;
    }
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        return recursion(nums, 0, nums.size() - 1);
    }
};
相关推荐
徐小黑ACG3 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
Navigator_Z4 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
北极有牛4 小时前
cpp学习笔记--常量指针
java·开发语言·算法
GPU实战笔记4 小时前
云端 GPU 训练的账户余额提醒:它能说明什么,不能说明什么?
深度学习·算法·成本管理·gpu云计算·云端训练
浮链序5 小时前
怎么证明"你这个模型是偷我的"——把蒸馏变成取证工具
算法·安全·llm
小O的算法实验室5 小时前
IEEE TMC,面向异构物联网的多目标量子行为拓扑优化算法
算法
圣保罗的大教堂5 小时前
leetcode 301. 删除无效的括号 困难
leetcode
liliangcsdn5 小时前
派息率指标的应用探索和分析
大数据·算法
垆边人似月.6 小时前
华为机试题 :两数之和
c++·算法·华为
默默开发6 小时前
物流行业可用算法方向
算法