码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-02-24 22:27:01      阅读:287      评论:0      收藏:0      [点我收藏+]

标签:

题目来源:

  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

 

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

标签:

原文地址:http://www.cnblogs.com/chruny/p/5215121.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!