Leetcode Problem 108. Convert Sorted Array to Binary Search Tree

108. Convert Sorted Array to Binary Search Tree

Leetcode Solutions

Preorder Traversal: Always Choose Left Middle Node as a Root

  1. Define a helper function helper(left, right) that takes the indices of the current subarray as arguments.
  2. If left > right, the subarray is empty, and we return None.
  3. Calculate the middle index p = (left + right) // 2.
  4. Create a new tree node root with the value nums[p].
  5. Recursively construct the left subtree using the indices left to p - 1.
  6. Recursively construct the right subtree using the indices p + 1 to right.
  7. Assign the left and right subtrees to root.left and root.right respectively.
  8. Return the root node.
  9. Call helper(0, len(nums) - 1) to initiate the recursion and construct the BST.
UML Thumbnail

Preorder Traversal: Always Choose Right Middle Node as a Root

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...