Bird
Raised Fist0
DSA Pythonprogramming~10 mins

Convert Sorted Array to Balanced BST in DSA Python - Execution Trace

Choose your learning style10 modes available
Concept Flow - Convert Sorted Array to Balanced BST
Start with sorted array
↓
Find middle element
→Create root node with middle
↓
Left subarray
→Recursively build left subtree
↓
Right subarray
→Recursively build right subtree
↓
Attach left and right subtrees to root
↓
Return root node of balanced BST
Split the sorted array by middle element to create root, then recursively build left and right subtrees from subarrays.
Execution Sample
DSA Python
def sorted_array_to_bst(arr):
    if not arr:
        return None
    mid = len(arr) // 2
    root = TreeNode(arr[mid])
    root.left = sorted_array_to_bst(arr[:mid])
    root.right = sorted_array_to_bst(arr[mid+1:])
    return root
This code converts a sorted array into a balanced binary search tree by recursively choosing the middle element as root.
Execution Table
StepOperationSubarrayNode CreatedPointer ChangesVisual State
1Start with full array[1, 2, 3, 4, 5, 6, 7]NoneNoneEmpty tree
2Find middle[1, 2, 3, 4, 5, 6, 7]4root = 44
3Build left subtree[1, 2, 3]Noneroot.left pending4 -> left subtree pending
4Find middle[1, 2, 3]2root.left = 24 / 2
5Build left subtree[1]None2.left pending4 / 2 -> left subtree pending
6Find middle[1]12.left = 14 / 2 / 1
7Build left subtree[]None1.left = None4 / 2 / 1 (leaf)
8Build right subtree[]None1.right = None4 / 2 / 1 (leaf)
9Build right subtree[3]None2.right pending4 / 2 / \ 1 right subtree pending
10Find middle[3]32.right = 34 / 2 / \ 1 3
11Build left subtree[]None3.left = None4 / 2 / \ 1 3 (leaf)
12Build right subtree[]None3.right = None4 / 2 / \ 1 3 (leaf)
13Build right subtree[5, 6, 7]Noneroot.right pending4 / \ 2 right subtree pending
14Find middle[5, 6, 7]6root.right = 64 / \ 2 6
15Build left subtree[5]None6.left pending4 / \ 2 6 /
16Find middle[5]56.left = 54 / \ 2 6 / 5
17Build left subtree[]None5.left = None4 / \ 2 6 / 5 (leaf)
18Build right subtree[]None5.right = None4 / \ 2 6 / 5 (leaf)
19Build right subtree[7]None6.right pending4 / \ 2 6 / \ 5 right subtree pending
20Find middle[7]76.right = 74 / \ 2 6 / \ 5 7
21Build left subtree[]None7.left = None4 / \ 2 6 / \ 5 7 (leaf)
22Build right subtree[]None7.right = None4 / \ 2 6 / \ 5 7 (leaf)
23Return rootFull tree builtNoneNoneBalanced BST complete
💡 All subarrays empty, recursion ends, full balanced BST constructed
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 6After Step 10After Step 14Final
arr[1,2,3,4,5,6,7][1,2,3,4,5,6,7][1,2,3][1][3][5,6,7][1,2,3,4,5,6,7]
midNone31001None
rootNone421364
root.leftNoneNone22222
root.rightNoneNoneNoneNoneNone66
Key Moments - 3 Insights
Why do we pick the middle element as root?
Choosing the middle element (see Step 2, 4, 6, 10, 14) ensures the tree stays balanced by evenly splitting the array into left and right subtrees.
What happens when the subarray is empty?
When the subarray is empty (see Steps 7, 8, 11, 12, 17, 18, 21, 22), the function returns None, marking a leaf node's child, stopping recursion.
How do left and right pointers get assigned?
After creating a node, recursive calls assign left and right children (see Steps 4, 6, 10, 14, 16, 20). The pointers root.left and root.right are updated accordingly.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what node is created at Step 14?
ANode with value 6
BNode with value 5
CNode with value 7
DNode with value 4
💡 Hint
Check the 'Node Created' column at Step 14 in the execution_table
At which step does the recursion return None for the left subtree of node 1?
AStep 11
BStep 8
CStep 7
DStep 17
💡 Hint
Look for empty subarray returns under node 1 in execution_table Steps 7 and 8
If the input array was [1,2,3], what would be the root node value?
A1
B2
C3
DNone
💡 Hint
Recall the middle element is chosen as root; see variable_tracker for mid calculation
Concept Snapshot
Convert Sorted Array to Balanced BST:
- Pick middle element as root
- Recursively build left subtree from left subarray
- Recursively build right subtree from right subarray
- Base case: empty subarray returns None
- Ensures balanced BST with O(log n) height
Full Transcript
This concept converts a sorted array into a balanced binary search tree by recursively selecting the middle element as the root node. The process splits the array into left and right subarrays, building left and right subtrees respectively. When the subarray is empty, recursion stops by returning None, marking leaf nodes. This approach ensures the tree remains balanced, with roughly equal nodes on each side, resulting in efficient search operations. The execution table traces each step, showing node creation, pointer assignments, and the evolving tree structure. Variable tracking shows how the array, middle index, and root pointers change during recursion. Key moments clarify why the middle element is chosen, how empty subarrays end recursion, and how pointers are assigned. Visual quizzes test understanding of node creation steps, recursion base cases, and root selection for smaller arrays.

Practice

(1/5)
1. What is the main goal when converting a sorted array to a balanced Binary Search Tree (BST)?
easy
A. To create a BST with minimal height
B. To create a linked list from the array
C. To reverse the array elements
D. To sort the array again

Solution

  1. Step 1: Understand the problem goal

    The goal is to convert a sorted array into a BST that is balanced, meaning the tree height is minimized for efficient operations.
  2. Step 2: Reason about balanced BST

    A balanced BST has roughly equal nodes on left and right subtrees, which reduces height and improves search time.
  3. Final Answer:

    To create a BST with minimal height -> Option A
  4. Quick Check:

    Balanced BST = minimal height [OK]
Hint: Pick option about minimal height balanced BST [OK]
Common Mistakes:
  • Thinking the array is reversed
  • Confusing BST with linked list
  • Ignoring balance and height
2. Which of the following Python function signatures is correct for converting a sorted array nums to a balanced BST using recursion?
easy
A. def sortedArrayToBST(nums: list) -> int:
B. def sortedArrayToBST(nums: int) -> TreeNode:
C. def sortedArrayToBST(nums: list[int]) -> Optional[TreeNode]:
D. def sortedArrayToBST(nums: list[int]) -> list[int]:

Solution

  1. Step 1: Check parameter type

    The input is a sorted array, so nums should be a list of integers: list[int].
  2. Step 2: Check return type

    The function returns the root of a BST, which is a TreeNode or None, so Optional[TreeNode] is correct.
  3. Final Answer:

    def sortedArrayToBST(nums: list[int]) -> Optional[TreeNode]: -> def sortedArrayToBST(nums: list[int]) -> Optional[TreeNode]:
  4. Quick Check:

    Input list[int], output Optional[TreeNode] [OK]
Hint: Look for list input and TreeNode output signature [OK]
Common Mistakes:
  • Using int instead of list[int] for input
  • Returning int or list instead of TreeNode
  • Missing Optional for possible None return
3. What is the output tree structure (inorder traversal) after running this code?
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def sortedArrayToBST(nums):
    if not nums:
        return None
    mid = len(nums) // 2
    root = TreeNode(nums[mid])
    root.left = sortedArrayToBST(nums[:mid])
    root.right = sortedArrayToBST(nums[mid+1:])
    return root

root = sortedArrayToBST([-10, -3, 0, 5, 9])

# Inorder traversal function
def inorder(node):
    return inorder(node.left) + [node.val] + inorder(node.right) if node else []

print(inorder(root))
medium
A. [0, -10, -3, 5, 9]
B. [-10, -3, 0, 5, 9]
C. [9, 5, 0, -3, -10]
D. [5, 9, 0, -3, -10]

Solution

  1. Step 1: Understand inorder traversal

    Inorder traversal of a BST returns the sorted array in ascending order.
  2. Step 2: Trace the code output

    The code builds a balanced BST from the sorted array, so inorder traversal returns the original sorted array: [-10, -3, 0, 5, 9].
  3. Final Answer:

    [-10, -3, 0, 5, 9] -> Option B
  4. Quick Check:

    Inorder traversal = sorted array [OK]
Hint: Inorder traversal of BST equals sorted array [OK]
Common Mistakes:
  • Confusing preorder or postorder with inorder
  • Expecting reversed or shuffled output
  • Not understanding recursion splits
4. Identify the error in this code snippet for converting a sorted array to a balanced BST:
def sortedArrayToBST(nums):
    if len(nums) == 0:
        return None
    mid = len(nums) // 2
    root = TreeNode(nums[mid])
    root.left = sortedArrayToBST(nums[mid+1:])
    root.right = sortedArrayToBST(nums[:mid])
    return root
medium
A. TreeNode initialization missing value
B. Mid index calculation is incorrect
C. Base case condition is wrong
D. Left and right subtree slices are swapped

Solution

  1. Step 1: Check subtree assignments

    The left subtree should be built from elements before mid: nums[:mid], and right subtree from elements after mid: nums[mid+1:].
  2. Step 2: Identify swapped slices

    The code assigns left subtree from nums[mid+1:] and right subtree from nums[:mid], which is reversed.
  3. Final Answer:

    Left and right subtree slices are swapped -> Option D
  4. Quick Check:

    Left subtree = nums[:mid], right subtree = nums[mid+1:] [OK]
Hint: Remember left subtree < mid, right subtree > mid [OK]
Common Mistakes:
  • Swapping left and right subtree slices
  • Incorrect base case check
  • Wrong mid index calculation
5. Given a sorted array with duplicate values [1, 2, 2, 3, 4, 4, 5], which approach correctly builds a balanced BST that includes all duplicates?
hard
A. Always pick leftmost element as root to handle duplicates
B. Remove duplicates first, then build BST
C. Use middle element as root, recursively build left and right subtrees including duplicates
D. Build BST by inserting elements one by one from left to right

Solution

  1. Step 1: Understand duplicates in sorted array

    Duplicates appear consecutively; to keep all, do not remove them before building BST.
  2. Step 2: Balanced BST construction with duplicates

    Picking the middle element as root and recursively building left and right subtrees preserves duplicates and balance.
  3. Final Answer:

    Use middle element as root, recursively build left and right subtrees including duplicates -> Option C
  4. Quick Check:

    Middle element root keeps duplicates balanced [OK]
Hint: Keep duplicates, use middle element recursively [OK]
Common Mistakes:
  • Removing duplicates before building BST
  • Picking always leftmost element as root
  • Inserting elements one by one causing imbalance
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard