• [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
  • 相关阅读:
    linux 网卡配置详情
    linux ftp 添加用户及权限管理
    mysql 权限管理
    linux ftp 安装及相关命令
    linux find 命令
    linux yum 安装及卸载
    linux svn 安装
    cssText方式写入css
    addLoadEvent
    mobile体验效果:增加点击后反馈
  • 原文地址:https://www.cnblogs.com/chruny/p/5215121.html
Copyright © 2020-2023  润新知