LeetCode Solutions

654. Maximum Binary Tree

Time: $O(n^2)$

Space: $O(h)$

			

class Solution {
 public:
  TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
    return build(nums, 0, nums.size() - 1);
  }

 private:
  TreeNode* build(const vector<int>& nums, int i, int j) {
    if (i > j)
      return nullptr;

    const auto it = max_element(begin(nums) + i, begin(nums) + j + 1);
    const int maxNum = *it;
    const int maxIndex = it - begin(nums);

    TreeNode* root = new TreeNode(maxNum);
    root->left = build(nums, i, maxIndex - 1);
    root->right = build(nums, maxIndex + 1, j);
    return root;
  }
};
			

class Solution {
  public TreeNode constructMaximumBinaryTree(int[] nums) {
    return build(nums, 0, nums.length - 1);
  }

  private TreeNode build(int[] nums, int i, int j) {
    if (i > j)
      return null;

    int maxIndex = i;
    for (int k = i + 1; k <= j; ++k)
      if (nums[k] > nums[maxIndex])
        maxIndex = k;

    TreeNode root = new TreeNode(nums[maxIndex]);
    root.left = build(nums, i, maxIndex - 1);
    root.right = build(nums, maxIndex + 1, j);
    return root;
  }
}
			

class Solution:
  def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
    def build(i: int, j: int) -> Optional[TreeNode]:
      if i > j:
        return None

      maxNum = max(nums[i:j + 1])
      maxIndex = nums.index(maxNum)

      root = TreeNode(maxNum)
      root.left = build(i, maxIndex - 1)
      root.right = build(maxIndex + 1, j)
      return root

    return build(0, len(nums) - 1)