其他分享
首页 > 其他分享> > 654.maximum-binary-tree 最大二叉树

654.maximum-binary-tree 最大二叉树

作者:互联网

递归就好了,没啥好说的。

class Solution {
  private:
    int getMax(vector<int> &nums, int l, int r) {
        int m_index = l;
        for (int i = l; i < r; i++) {
            if (nums[i] >= nums[m_index])
                m_index = i;
        }
        return m_index;
    }
    TreeNode *build_tree(vector<int> &nums, int l, int r) {
        if (l == r)
            return nullptr;
        int mid = getMax(nums, l, r);
        TreeNode *root = new TreeNode(nums[mid]);
        root->left = build_tree(nums, l, mid);
        root->right = build_tree(nums, mid + 1, r);
        return root;
    }

  public:
    TreeNode *constructMaximumBinaryTree(vector<int> &nums) {
        return build_tree(nums, 0, nums.size());
    }
};

标签:binary,TreeNode,nums,int,index,tree,mid,二叉树
来源: https://www.cnblogs.com/zwyyy456/p/16654307.html