Back to Leetcode Go

95. Unique Binary Search Trees II

website/content.en/ChapterFour/0001~0099/0095.Unique-Binary-Search-Trees-II.md

1.7.971.7 KB
Original Source

95. Unique Binary Search Trees II

Problem

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.

Example:

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

Problem Summary

Given an integer n, generate all binary search trees composed of nodes with values from 1 ... n.

Solution Approach

  • Output all solutions of BSTs composed of elements 1n. This problem can be solved recursively. The outer loop traverses all nodes from 1n as the root node, and the inner double recursion obtains the left subtree and right subtree respectively.

Code

go

package leetcode

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func generateTrees(n int) []*TreeNode {
	if n == 0 {
		return []*TreeNode{}
	}
	return generateBSTree(1, n)
}

func generateBSTree(start, end int) []*TreeNode {
	tree := []*TreeNode{}
	if start > end {
		tree = append(tree, nil)
		return tree
	}
	for i := start; i <= end; i++ {
		left := generateBSTree(start, i-1)
		right := generateBSTree(i+1, end)
		for _, l := range left {
			for _, r := range right {
				root := &TreeNode{Val: i, Left: l, Right: r}
				tree = append(tree, root)
			}
		}
	}
	return tree
}