Leetcode 95. Unique Binary Search Trees II

Gary Chiang
Sep 2, 2021

--

[medium]

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 1:

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]]

Example 2:

Input: n = 1
Output: [[1]]

Constraints:

  • 1 <= n <= 8

[Java]

  1. Think: will need a arraylist for the answer(TreeNode in the list)
  2. will need to use recursive to do the in-order traversal
  3. generate left subtree and right subtree, add them with the root, and recursive multiple situation.
  4. Trick: left = genTrees(start, i-1), right = genTrees(i+1, end)

--

--

Gary Chiang
Gary Chiang

Written by Gary Chiang

CS new grad, 6 years experience related to supply chain management. Located in Bay area

No responses yet