leetcode--108--transforming an ordered array into a two-fork search tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.