题目要求
给定一个整数 n,生成所有由 1 … n 为节点所组成的二叉搜索树。
解题思路
所以我们节点是从1到n,当一个节点为val那么它的左边是<= val,右边是>=val,
我们用递归左右子树一步步解决!
for l in helper(start, val-1):
for r in helper(val+1, end):
主要代码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]
"""
def helper(start,end):
res = []
if start > end:
return [None]
for val in range(start, end+1):
# 按BST要求划分左边都是小于val的,右边都是大于val的
# 递归操作
for l in helper(start, val-1):
for r in helper(val+1, end):
# 建树过程
root = TreeNode(val)
root.left = l
root.right = r
res.append(root)
return res
return helper(1,n) if n else []