Problem Description:
Converts an ordered array in ascending order to a highly balanced binary search tree.
In the subject, a highly balanced binary tree refers to the absolute value of the height difference of the left and right two subtrees of each node of a binary tree not exceeding 1.
Example:
Given an ordered array: [ -10,-3,0,5,9], one possible answer is: [0,-3,9,-10,null,5], which can represent the following highly balanced binary search tree: 0 / -3 9 / /-10 5
Idea: Because the array is an ordered array, so just use the binary method to construct, mid is the root node, the middle point of the 0:mid is the root node of Zuozi, mid+1: The middle point at the end is the root node of the right subtree, recursive construction can be.
Method 1:
1 classsolution (object):2 defSortedarraytobst (Self, nums):3 """4 : Type Nums:list[int]5 : Rtype:treenode6 """7 ifNums:8Midpos = Len (nums)//29MID =Nums[midpos]TenRoot =TreeNode (mid) OneRoot.left =Self.sortedarraytobst (Nums[:midpos]) ARoot.right = Self.sortedarraytobst (nums[midpos+1:]) - returnRoot
2018-09-09 16:00:01
leetcode--108--transforming an ordered array into a two-fork search tree