不同的二叉搜索树 II
程序员文章站
2022-06-17 19:50:24
...
Python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n <= 0 :return []
nums = range(1,n+1)
return self.generateSubTree(nums)
def generateSubTree(self,num_list):
ans = []
if not num_list:return [None]
for index in range(len(num_list)):
left_list = self.generateSubTree(num_list[:index])
right_list = self.generateSubTree(num_list[index+1:])
for i in left_list:
for j in right_list:
tree = TreeNode(num_list[index])
tree.left = i
tree.right = j
ans.append(tree)
return ans