109.Convert Sorted List to Binary Search Tree Leetcode Python

Source: Internet
Author: User

Convert Sorted List to Binary Search Tree total accepted:32343 total submissions:117376 My submissions Question Solution

Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST


The question and convert array to binary search tree differ in that there is no random access with LinkedList so to find the midpoint you can only use fast and slow pointer to find.

This method is slower than turning the LinkedList directly into an array.


The code is as follows:

# Definition for a  binary tree node# class treenode:#     def __init__ (self, x): #         self.val = x#         self.left = No ne#         self.right = none## Definition for singly-linked list.# class listnode:#     def __init__ (self, x): #         Self.val = x#         self.next = Noneclass solution:    # @param head, a list node    # @return A tree node    def conver T (self,head,tail):        if Head==tail:            return None        if Head.next==tail:            return TreeNode (head.val)        mid=head        Fast=head while        fast!=tail and Fast.next!=tail:            fast=fast.next.next            mid= Mid.next        Node=treenode (mid.val)        Node.left=self.convert (head,mid)        Node.right=self.convert ( Mid.next,tail)        return node    def sortedlisttobst (self, head):        return Self.convert (Head,none)        


109.Convert Sorted List to Binary Search Tree leetcode Python

Related Article

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.