标签:
题目来源:
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
[LeetCode]题解(python):108-Convert Sorted Array to Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/chruny/p/5258311.html