Leetcode convert Sorted Array to Binary Search tree original problem
Given an ascending sequence, turn it into a highly balanced two-fork search tree.
Note the point:
- A two-fork search tree of the same sequence may have multiple
Example:
Input: Nums = [+]
Output:
1 3
Thinking of solving problems
The requirement for a balanced binary search tree is that the height difference between the left and right subtrees of each node is up to 1. As long as the middle number of the sequence as the root node, the left sequence is composed of its left sub-tree, the right of the sequence of its right subtree, recursive completion of the construction.
AC Source
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x):Self.val = x Self.left =NoneSelf.right =None class solution(object): def sortedarraytobst(self, nums): "" : Type Nums:list[int]: Rtype:treenode " " " returnSelf._sortedarraytobst (Nums,0, Len (nums)) def _sortedarraytobst(self, nums, left, right): ifleft = = Right:return NoneMid = (left + right) >>1Root = TreeNode (Nums[mid]) Root.left = Self._sortedarraytobst (Nums, left, mid) Root.right = Self._sortedarra Ytobst (Nums, Mid +1, right)returnRootif__name__ = ="__main__":None
Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.
Leetcode Convert Sorted Array to Binary Search Tree