KatInterview

654. Maximum Binary Tree

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to construct a special kind of binary tree, called a Maximum Binary Tree, from an array of unique integers. The construction rules are defined recursively:

Solution

Maximum Binary Tree in 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]:
        # Using a helper function with indices is more memory-efficient
        # than using slicing, which creates copies of the list.
        def build(left: int, right: int) -> Optional[TreeNode]:
            # Base case: if the range is invalid, the subarray is empty, so return None.
            if left > right:
                return None

            # Find the index of the maximum element in the current range nums[left:right+1].
            max_idx = left
            for i in range(left + 1, right + 1):
                if nums[i] > nums[max_idx]:
                    max_idx = i
            
            # Create the root node with the maximum value.
            root = TreeNode(nums[max_idx])
            
            # Recursively build the left subtree on the prefix to the left of the maximum.
            root.left = build(left, max_idx - 1)
            # Recursively build the right subtree on the suffix to the right of the maximum.
            root.right = build(max_idx + 1, right)
            
            return root

        # Initial call to the recursive helper function for the entire array.
        return build(0, len(nums) - 1)

Maximum Binary Tree in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        // Initial call to the recursive helper function for the entire array.
        return build(nums, 0, nums.length - 1);
    }

    private TreeNode build(int[] nums, int left, int right) {
        // Base case: if the range is invalid, the subarray is empty, so return null.
        if (left > right) {
            return null;
        }

        // Find the index of the maximum element in the current range [left, right].
        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 root = new TreeNode(nums[maxIndex]);

        // Recursively build the left subtree on the prefix of the subarray to the left of the maximum value.
        root.left = build(nums, left, maxIndex - 1);

        // Recursively build the right subtree on the suffix of the subarray to the right of the maximum value.
        root.right = build(nums, maxIndex + 1, right);

        // Return the constructed root of the subtree.
        return root;
    }
}

Maximum Binary Tree in C++

/**
 * 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) {
        // Initial call to the recursive helper function for the entire array.
        return build(nums, 0, nums.size() - 1);
    }

private:
    TreeNode* build(vector<int>& nums, int left, int right) {
        // Base case: if the range is invalid, the subarray is empty, so return null.
        if (left > right) {
            return nullptr;
        }

        // Find the index of the maximum element in the current range [left, right].
        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* root = new TreeNode(nums[maxIndex]);

        // Recursively build the left subtree on the prefix of the subarray to the left of the maximum value.
        root->left = build(nums, left, maxIndex - 1);
        
        // Recursively build the right subtree on the suffix of the subarray to the right of the maximum value.
        root->right = build(nums, maxIndex + 1, right);

        // Return the constructed root of the subtree.
        return root;
    }
};

Maximum Binary Tree in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function constructMaximumBinaryTree(nums: number[]): TreeNode | null {
    
    // Recursive helper function to build the tree from a subarray defined by indices.
    function build(left: number, right: number): TreeNode | null {
        // Base case: if the range is invalid, the subarray is empty, so return null.
        if (left > right) {
            return null;
        }

        // Find the index of the maximum element in the current range [left, right].
        let maxIndex = left;
        for (let i = left + 1; i <= right; i++) {
            if (nums[i] > nums[maxIndex]) {
                maxIndex = i;
            }
        }

        // Create the root node with the maximum value.
        const root = new TreeNode(nums[maxIndex]);

        // Recursively build the left subtree on the prefix of the subarray to the left of the maximum value.
        root.left = build(left, maxIndex - 1);

        // Recursively build the right subtree on the suffix of the subarray to the right of the maximum value.
        root.right = build(maxIndex + 1, right);

        // Return the constructed root of the subtree.
        return root;
    }
    
    // Initial call to the recursive helper function for the entire array.
    return build(0, nums.length - 1);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.