LeetCode 095 Unique Binary Search Trees II

LeetCode 095 Unique Binary Search Trees II Problem

Download Code
# 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 []
        return self.get_trees(1, n)

    def get_trees(self, start, end):
        # recursive solve this problem
        res = []
        if start > end:
            return res
        for i in range(start, end + 1):
            lefts = self.get_trees(start, i - 1)
            rights = self.get_trees(i + 1, end)
            for j in range(len(lefts)):
                for k in range(len(rights)):
                    # root point
                    root = TreeNode(i)
                    root.left = lefts[j]
                    root.right = rights[k]
        return res

Download Unique Binary Search Trees II.py

List of all Unique Binary Search Trees II problems

Leetcode 095 Unique Binary Search Trees II problem solution in python3 with explanation. This is the best place to expand your knowledge and get prepared for your next interview.

self.val = x

Feedback is the most important part of any website.

If you have any query, suggestion or feedback, Please feel free to contact us.