zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):108-Convert Sorted Array to Binary Search Tree

    题目来源:

      https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/


    题意分析:

      给出一个排好序的数组,根据这个数据形成一个高度平衡的搜索二叉树。


    题目思路:

      将中位数为根节点,中位数左边为左子树,右边为右子树。


    代码(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 sortedArrayToBST(self, nums):
            """
            :type nums: List[int]
            :rtype: TreeNode
            """
            size = len(nums)
            if size == 0:
                return None
            if size == 1:
                return TreeNode(nums[0])
            size //= 2
            root = TreeNode(nums[size])
            root.left = self.sortedArrayToBST(nums[:size])
            root.right = self.sortedArrayToBST(nums[size + 1:])
            return root
            
    View Code
  • 相关阅读:
    TASK1
    CSS再学
    Html再学
    Python的hasattr() getattr() setattr() 函数使用方法详解
    GET/POST/g和钩子函数(hook)
    cookie和session
    SQLAlchemy外键的使用
    jquery树形菜单插件treeView
    linux设置防火墙
    linux解压命令
  • 原文地址:https://www.cnblogs.com/chruny/p/5258311.html
Copyright © 2011-2022 走看看