美文网首页
95. Unique Binary Search Trees I

95. Unique Binary Search Trees I

作者: 羲牧 | 来源:发表于2020-07-19 17:59 被阅读0次

    将1到n的序列,选定任意一个数为根节点,然后分别求解左右字树的解。
    同时递归求解左右子树。

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def generateTrees(self, n: int) -> List[TreeNode]:
            if n <= 0:
                return []
            return self.helper(1, n)
        
        def helper(self, start, end):
            if start > end:
                return [None]
            result = []
            for i in range(start, end+1):
                left = self.helper(start, i-1)
                right = self.helper(i+1, end)
                for e in left:
                    for f in right:
                        node = TreeNode(i)
                        node.left = e
                        node.right = f
                        result.append(node)
            return result
            
    

    相关文章

      网友评论

          本文标题:95. Unique Binary Search Trees I

          本文链接:https://www.haomeiwen.com/subject/audrkktx.html