【leetcode】(python)108. Convert Sorted Array to Binary Search Tree将有序数组转换为二叉树

it2022-05-05  119

将有序数组转换为二叉树

DescriptionExample题意解题思路code 108. Convert Sorted Array to Binary Search Tree Easy

Description

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

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

题意

将有序数组转化为对应的二叉树。

解题思路

求解树的问题应首先找出根结点,然后看能不能递归,如何递归实现。这题给定的是有序数组,那么对应的应该是一个先序遍历递增的二叉树,那么找到根结点后,根结点左边对应左子树,根结点右边对应右子树。

code

# 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, nums: List[int]) -> TreeNode: if len(nums) == 0: return None if len(nums) == 1: return TreeNode(nums[0]) r = len(nums) // 2 root = TreeNode(nums[r]) root.left = self.sortedArrayToBST(nums[:r]) root.right = self.sortedArrayToBST(nums[r+1:]) return root

最新回复(0)