编程语言
首页 > 编程语言> > LeetCode题目记录-654. 最大二叉树(C++代码实现)

LeetCode题目记录-654. 最大二叉树(C++代码实现)

作者:互联网

题目链接:

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

题目要求:

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 {
public:

    //digui
    TreeNode* digui(vector<int>& nums,int begin,int end){
        if(begin > end){
            return nullptr;
        }

        //得到当前范围内的最大值索引
        int maxIndex = getCurrIndex(nums,begin,end);
        //构造根节点
        TreeNode* root = new TreeNode(nums[maxIndex]);

        root->left = digui(nums,begin,maxIndex - 1);
        root->right = digui(nums,maxIndex + 1,end);

        return root;
    }

    //得到最大索引值的方法
    int getCurrIndex(vector<int>& nums,int begin,int end){

        int maxIndex = INT_MIN;
        int maxNum = INT_MIN;

        for(int i = begin;i <= end;i++){
            if(nums[i] > maxNum){
                maxIndex = i;
                maxNum = nums[i];
            }
        }

        return maxIndex;
    }


    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        int n = nums.size();
        TreeNode* root = digui(nums,0,n - 1);

        return root;
    }
};

AC截图

 

本题解仅作为个人复习查看使用,并无他用。 

标签:right,TreeNode,nums,int,maxIndex,C++,654,二叉树,left
来源: https://blog.csdn.net/weixin_43749999/article/details/121888128