bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 654. Maximum Binary Tree

654. Maximum Binary Tree

Leetcode Solutions

Recursive Construction of Maximum Binary Tree

  1. Define a recursive function construct(nums, l, r) that takes a subarray defined by indices l and r.
  2. If l == r, return None as there are no elements to form a tree.
  3. Find the index max_i of the maximum element in the subarray nums[l:r].
  4. Create a new tree node root with the value nums[max_i].
  5. Recursively construct the left subtree with construct(nums, l, max_i) and assign it to root.left.
  6. Recursively construct the right subtree with construct(nums, max_i + 1, r) and assign it to root.right.
  7. Return the root node.
UML Thumbnail

Iterative Construction with Stack

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...