[LeetCode]题解(python):095-Unique Binary Search Trees II

题目来源:

  https://leetcode.com/problems/unique-binary-search-trees-ii/


 

题意分析:

  给一个整数,返回所有中序遍历是1到n的树。


 

题目思路:

  这可以用递归的思想。首先确定根节点,如果k是根节点,那么1-k-1是左子树,而k+1-n为右子树。


 

代码(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 []
        def solve(begin,end):
            if begin > end:
                return [None]
            i = begin
            ans = []
            while i <= end:
                tmp1,tmp2 = solve(begin, i - 1),solve(i + 1,end)
                for j in tmp1:
                    for k in tmp2:
                        tmp = TreeNode(i)
                        tmp.left = j
                        tmp.right = k
                        ans.append(tmp)
                i += 1
            return ans
        return solve(1,n)
                    
View Code

 

posted @ 2016-02-24 20:45  Ry_Chen  阅读(190)  评论(0编辑  收藏  举报