1、題目描述
https://leetcode-cn.com/problems/unique-binary-search-trees-ii/
給定一個整數 n,生成所有由 1 ... n 爲節點所組成的 二叉搜索樹 。0 <= n <= 8
相關題:96. 不同的二叉搜索樹(多少種) https://blog.csdn.net/IOT_victor/article/details/107066267
2、代碼詳解
遞歸法
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n == 0:
return []
return self.dfs(1, n)
def dfs(self, start, end):
if start > end:
return [None]
res = []
for rootval in range(start, end + 1): # 選一個root
LeftTree = self.dfs(start, rootval - 1) # 左子樹所有可能
RightTree = self.dfs(rootval + 1, end) # 右子樹所有可能
# 連接在一起
for i in LeftTree:
for j in RightTree:
root = TreeNode(rootval)
root.left = i
root.right = j
res.append(root)
return res