Leetcode Convert Sorted Array to Binary Search Tree

Source: Internet
Author: User

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

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.