zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    Beetl模板 [记录]
    wx 小程序开发 [记录]
    高德定位获取省市区[记录]
    vue 学习记录 [记录]
    正则表达+验证 [记录]
    倒计时60s短信 [记录]
    @media [记录]
    JSON + Ajax [记录]
    Webstorm [记录]
    JQ 组合代码 [记录]
  • 原文地址:https://www.cnblogs.com/chruny/p/5215121.html
Copyright © 2011-2022 走看看