Maximum Binary Tree — LeetCode 654 Python Solution

MediumStackTreeArrayDivide and ConquerBinary TreeMonotonic Stack
Problem
#654
Pattern
Stack
Reading time
4 min

The problem

You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm: Create a root node whose value is the maximum value in nums.

Example

Input
nums = [3,2,1,6,0,5]
Output
[6,3,5,null,2,0,null,null,1]
Explanation
The recursive calls are as follow:

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
        def dfs(nums):
            if not nums:
                return None
            val = max(nums)
            i = nums.index(val)
            root = TreeNode(val)
            root.left = dfs(nums[:i])
            root.right = dfs(nums[i + 1 :])
            return root

        return dfs(nums)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 654. Maximum Binary Tree is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 654. Maximum Binary Tree?
LeetCode 654. Maximum Binary Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 654. Maximum Binary Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 654. Maximum Binary Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 654. Maximum Binary Tree cover?
LeetCode 654. Maximum Binary Tree is tagged Stack, Tree, Array, Divide and Conquer, Binary Tree and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview