前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q108 Convert Sorted Array to Binary Search Tree

Q108 Convert Sorted Array to Binary Search Tree

作者头像
echobingo
发布2018-04-25 16:48:21
4840
发布2018-04-25 16:48:21
举报

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

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.

Example:
代码语言:javascript
复制
Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], 
which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5
解题思路:

首先明白平衡二叉树的定义,注意要是每个结点必须满足。因为是将一个有序数组转化为一个平衡二叉树,因此,答案可能不唯一。

递归,将中间元素作为根节点,然后将数组分为左右两部分。左边数组用于递归创建左子树,右边数组用于递归创建右子树,直到数组为空。

Python实现:
代码语言:javascript
复制
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sortedArrayToBST(self, num):
        if not num:   # 如果数组为空
            return None
        mid = len(num) // 2
        root = TreeNode(num[mid])
        root.left = self.sortedArrayToBST(num[:mid])     # 递归构建左子树
        root.right = self.sortedArrayToBST(num[mid+1:])  # 递归构建右子树
        return root
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.02.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example:
  • 解题思路:
  • Python实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档