Unique Binary Search Trees Ii

To solve this coding challenge of generating all structurally unique Binary Search Trees (BSTs) with exactly \( n \) nodes containing unique values from 1 to \( n \), we can leverage a recursive approach. This approach will recursively construct BSTs by choosing each possible root and then generating left and right subtrees, ensuring all combinations are considered.

Explanation:

The task requires generating all possible unique BSTs with nodes numbered from 1 to \( n \). To approach this problem, we need to:
  1. Decide a 'root' for our BST for each value from 1 to \( n \).
  2. Recursively generate all possible left subtrees using values less than the chosen root.
  3. Recursively generate all possible right subtrees using values greater than the chosen root.
  4. Combine the left and right subtrees with the root to create a BST.
  5. Store each unique combination generated in a result array.
  6. For instance, if \( n \) is 3, valid BSTs could be created by choosing 1, 2, or 3 as the root. This recursive approach ensures every possible BST structure is considered.

    Step-by-Step Explanation:

  7. Define the Recursive Function:
    • Given start and end indices, if the start is greater than the end, it returns an array containing
      null
      since this represents an empty tree.
  8. Iterate over All Possible Roots:
    • For each value \( i \) from
      start
      to
      end
      :
      • Generate all left subtrees with values from
        start
        to \( i-1 \).
      • Generate all right subtrees with values from \( i+1 \) to
        end
        .
  9. Construct Trees for Each Root:
    • Combine each left subtree with each right subtree to form a new tree with the current root.
    • Append this newly formed tree to the result array.
  10. Return the Result:
    • After iterating through all possible values for the root within the given range, return the result array containing all unique BSTs.

    Detailed Steps in Pseudocode:

                                                
    # Define a function to generate all unique BSTs
    function generateUniqueBSTs(n):
    # Helper function to generate BSTs for a given range
    function generateTrees(start, end):
    if start > end:
    return [null]  # Base case: When start is greater than end, return an array with null
    
    allTrees = []  # Initialize an array to store all unique BSTs
    
    # Iterate through all values from start to end to use each value as root
    for rootValue from start to end:
    # Recursively generate all left subtrees of the root
    leftSubtrees = generateTrees(start, rootValue - 1)
    # Recursively generate all right subtrees of the root
    rightSubtrees = generateTrees(rootValue + 1, end)
    
    # Combine each left subtree with each right subtree
    for left in leftSubtrees:  # Iterate through each left subtree
    for right in rightSubtrees:  # Iterate through each right subtree
    root = TreeNode(rootValue)  # Create a new tree node with the root value
    root.left = left  # Attach the left subtree
    root.right = right  # Attach the right subtree
    allTrees.append(root)  # Append the new tree to the result array
    
    return allTrees  # Return the array of all unique BSTs
    
    # Edge case when n = 0, return an empty array
    if n == 0:
    return []
    
    # Generate all unique BSTs for values from 1 to n
    return generateTrees(1, n)
    
                                            
  11. Initialization:
    • The main function
      generateUniqueBSTs(n)
      checks if \( n \) is zero. If true, it returns an empty list since there are no trees possible for zero nodes.
  12. Recursive Generation:
    • The helper function
      generateTrees(start, end)
      handles the recursive generation of BSTs for a given range of values.
    • It returns
      [null]
      if
      start
      is greater than
      end
      indicating no valid tree structure.
    • For each value within the range as the root, it generates all possible left and right subtrees and combines them to form a new tree.
  13. Tree Construction:
    • For each value serving as root, it constructs the tree by forming combinations of all left and right subtrees recursively and appends them to the
      allTrees
      array.
By following this detailed approach, we can ensure that all structurally unique BSTs within the given node range from 1 to \( n \) are generated.