Leetcode Convert Sorted List to Binary Search Tree

Source: Internet
Author: User

Leetcode convert Sorted List to Binary Search tree original problem

Given an ascending one-way list, 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 = 1->2->3

Output:

  1   3
Thinking of solving problems

This is the version of the convert Sorted Array to Binary Search Tree, which can be converted to a list before being answered. If the list is solved directly, it can be seen that the list is characterized by traversal from beginning to end, because it is incremented, so that is, from small to large in turn. And the result of the middle sequence traversal of the binary search tree is an ascending sequence, so it can be constructed by the way of the middle sequence traversal of the tree.

AC Source
# Definition for singly-linked list. class listnode(object):     def __init__(self, x):Self.val = x Self.next =None# 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 sortedlisttobst(self, head):        "" : Type Head:ListNode:rtype:TreeNode "" "node, length = Head,0         whileNode:node = node.next Length + =1Self.curr = HeadreturnSelf._sortedlisttobst (0, Length-1) def _sortedlisttobst(self, left, right):        ifLeft > right:return NoneMid = (left + right)//2left = Self._sortedlisttobst (left, mid-1) root = TreeNode (self.curr.val) Root.left = left Self.curr = Self.curr.next Root.right = self . _SORTEDLISTTOBST (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 List 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.