Leetcode 95: Unique Binary Search Trees II

grid47
grid47
Exploring patterns and algorithms
Oct 28, 2024 6 min read

A sequence of elegant trees gently forming in various, unique shapes.
Solution to LeetCode 95: Unique Binary Search Trees II Problem

Given an integer n, return all structurally unique binary search trees (BSTs) that can be constructed using the integers from 1 to n. Each tree should be a unique arrangement of nodes where each node contains a unique value from the set {1, 2, …, n}.
Problem
Approach
Steps
Complexity
Input: The input is a single integer n, where 1 <= n <= 8, representing the number of nodes in the binary search tree.
Example: Input: n = 3
Constraints:
• 1 <= n <= 8
Output: Return a list of all structurally unique binary search trees that can be constructed using the integers from 1 to n. The output trees should be returned in any order.
Example: Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
Constraints:
• The output must include all unique BSTs without duplicates.
Goal: The goal is to generate all possible unique BSTs for a given number n, where each BST is formed by placing integers 1 to n as nodes in a valid binary search tree structure.
Steps:
• Recursively fix a root node and divide the remaining numbers into left and right subtrees.
• Generate all possible left and right subtrees for each choice of root node.
• Combine each left and right subtree with the current root and add them to the result list.
Goal: The problem assumes that the input is within the given range and that all tree structures should be returned in valid BST format.
Steps:
• 1 <= n <= 8
• Each node must have a unique value from the set {1, 2, ..., n}.
• The output must contain all structurally unique BSTs, not just one possible arrangement.
Assumptions:
• The input number n is valid and within the specified range.
• The binary search tree properties (left children < root and right children > root) must hold for all trees.
Input: Input: n = 3
Explanation: For n = 3, the unique BSTs can be formed by choosing each number as the root once, and then generating the corresponding left and right subtrees. The output consists of 5 unique BSTs.

Input: Input: n = 1
Explanation: For n = 1, there is only one possible BST: a single node tree with value 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus