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

Solution: Divide and Conqur

We use a low and high pointer to mark the search area Each time we search for the max element in the range and create a new node Then we recursively call this function to get left child node and right child node.

Time Complexity : O(n^2)

TreeNode* helper(vector<int>& nums, int low, int high) {    
    if (low > high) return NULL;
    int max = low;
    for (int i=low; i<=high; i++) {
        if (nums[max] < nums[i]) max = i;
    }

    TreeNode *root = new TreeNode(nums[max]);
    root->left = helper(nums, low, max-1);
    root->right = helper(nums, max+1, high);
    return root;
}

TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
    return helper(nums, 0, nums.size()-1);
}

results matching ""

    No results matching ""