MediumNo. 0095
Unique Binary Search Trees II — LeetCode 95 Python Solution
- Pattern
- Backtracking
- Topics
- Tree, Binary Search Tree, Dynamic Programming, Backtracking, Binary Tree
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Example
- Input
- n = 3
- Output
- [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def generateTrees(self, n: int) -> List[Optional[TreeNode]]:
def dfs(i: int, j: int) -> List[Optional[TreeNode]]:
if i > j:
return [None]
ans = []
for v in range(i, j + 1):
left = dfs(i, v - 1)
right = dfs(v + 1, j)
for l in left:
for r in right:
ans.append(TreeNode(v, l, r))
return ans
return dfs(1, n)Complexity
- Time
- O(n × G(n))
- Space · auxiliary
- O(n × G(n))
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 95. Unique Binary Search Trees II is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0096 | Unique Binary Search Trees | Medium |
| 1373 | Maximum Sum BST in Binary Tree | Hard |
| 1569 | Number of Ways to Reorder Array to Get Same BST | Hard |
| 0124 | Binary Tree Maximum Path Sum | Hard |
| 0337 | House Robber III | Medium |
| 0894 | All Possible Full Binary Trees | Medium |
Frequently asked questions
- How hard is LeetCode 95. Unique Binary Search Trees II?
LeetCode 95. Unique Binary Search Trees II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 95. Unique Binary Search Trees II?
The Python solution on this page runs in O(n × G(n)).
- What is the space complexity of LeetCode 95. Unique Binary Search Trees II?
The Python solution on this page uses O(n × G(n)) auxiliary space.
- What topics does LeetCode 95. Unique Binary Search Trees II cover?
LeetCode 95. Unique Binary Search Trees II is tagged Tree, Binary Search Tree, Dynamic Programming, Backtracking and Binary Tree on LeetCode.