ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

leetcode108 Convert Sorted Array to Binary Search Tree

2020-02-28 15:03:33  阅读:184  来源: 互联网

标签:Node Binary Convert right nums self Tree convert left


 1 """
 2 Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
 3 For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
 4 Example:
 5 Given the sorted array: [-10,-3,0,5,9],
 6 One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
 7       0
 8      / \
 9    -3   9
10    /   /
11  -10  5
12 """
13 """
14 对于二叉搜索树,左右结点的值有规律,应该想到递归
15 二分+递归解法
16 """
17 class TreeNode:
18     def __init__(self, x):
19         self.val = x
20         self.left = None
21         self.right = None
22 
23 class Solution:
24     def sortedArrayToBST(self, nums):
25         return self.convert(nums, 0, len(nums) - 1)
26 
27     def convert(self, nums, left, right):
28         if left > right:  # bug 没写这个判断maximum recursion depth exceeded
29             return None
30         mid = (left + right) // 2
31         Node = TreeNode(nums[mid])
32         Node.left = self.convert(nums, left, mid - 1)
33         Node.right = self.convert(nums, mid + 1, right)
34         return Node

 

标签:Node,Binary,Convert,right,nums,self,Tree,convert,left
来源: https://www.cnblogs.com/yawenw/p/12377200.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有