Leetcode 654. Maximum Binary Tree
Given an integer array nums
, construct the maximum binary tree. The maximum binary tree is defined as follows:
nums
.Return the root node of the maximum binary tree.
#include <vector>
#include <algorithm>
using namespace std;
// 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* constructMaximumBinaryTree(vector<int>& nums) {
return construct(nums, 0, nums.size());
}
private:
TreeNode* construct(const vector<int>& nums, int left, int right) {
if (left == right) return nullptr;
// Find the index of the maximum value in the current range
int maxIndex = left;
for (int i = left + 1; i < right; ++i) {
if (nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
// Create the root node with the maximum value
TreeNode* node = new TreeNode(nums[maxIndex]);
// Recursively construct the left and right subtrees
node->left = construct(nums, left, maxIndex);
node->right = construct(nums, maxIndex + 1, right);
return node;
}
};
left
index equals right
index, return nullptr
.[left, right)
which will be the root for the current subtree.TreeNode
with the maximum value.construct
that takes the range [left, right)
as parameters.The time complexity for this approach is O(n^2) in the worst-case scenario:
n
times (for the most unbalanced tree).In the average case, the complexity tends to be better but is still bounded by O(n^2) due to unbalanced split possibilities.
For optimizing, a segment tree or a monotonic stack could potentially reduce the overhead to O(n) but increases implementation complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?