654 Maximum Binary Tree

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

The root is the maximum number in the array. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number. Construct the maximum tree by the given array and output the root node of this tree.

Example 1:

Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:

      6
    /   \
   3     5
    \    / 
     2  0   
       \
        1

Note: The size of the given array will be in the range [1,1000].

The Idea: The problem initially seemed intimidating, but narrowing it down to sub problems simplifies it greatly. Using iterators for the array is a natural way to doing things, since it cleanly defines the bounds of our start and end position of nums. Assuming the array is not empty, we begin with the maximum element in the array as the root. The left and right children of the root will then have the maximum element to the left and right of the maximum element respectively. If start == end, then we know the array is empty and therefore contains no maximum element, so return nullptr.

Complexity: O(n^2) time and O(n) space

TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
    return buildTree(nums.begin(), nums.end() - 1);         
}

template<typename iter>
TreeNode* buildTree(iter start, iter end) {
    if (start <= end) {
        auto max_iter = max_element(start, end + 1);
        TreeNode *root = new TreeNode(*max_iter);
        root->left = buildTree(start, max_iter - 1);
        root->right = buildTree(max_iter + 1, end);
        return root;
    }
    else return nullptr;
}

Last updated