Maximum Binary Tree

1 minute read

Construct the maximum tree by the given array and return the root node of this tree.

Question

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 return the root node of this tree.

Example:

Input: {3,2,1,6,0,5}
Output: Return the tree root node representing the following tree:
     6
   /   \
  3     5
   \   / 
    2 0   
     \
      1


Input: {1,2,3,4}
Output: Return the tree root node representing the following tree:
        4
       /
      3
     /
    2
   /
  1    

Analyzation

Recursion

Firstly, find the maximum number in the list.

Secondly, put this number into the tree

Thirdly, find the maximum number in the left subtree and find the maximum number in the right subtree recursively.

The Code

class Solution:
    """
    @param nums: an array
    @return: the maximum tree
    """
    def constructMaximumBinaryTree(self, nums):
        # Write your code here
        if len(nums) == 0:
            return None
            
        root_val = max(nums)
        root = TreeNode(root_val)
        root_index = nums.index(root_val)
        root.left = self.constructMaximumBinaryTree(nums[:root_index])
        root.right = self.constructMaximumBinaryTree(nums[root_index+1:])
        
        return root

Time & Space Complexity

  • Time complexity: O(n). Remember that the best case of a Binary Tree is O(logn) since it is a balanced tree but the worst case is O(n) because it can skew to only one side.
  • Space complexity: O(n). Remember that the space complexity is always about how many nodes there are in a Binary Tree. If the tree is well-balanced then it is O(logn) but the worst case will be O(n).