Convert Sorted List to Binary Search Tree

Source: Internet
Author: User

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

Since it is already ordered, the binary method is used to create this balanced binary tree, with the Sort List similar

Note that the second half of a chain of the index range is [0,high-mid-1], the original has been tangled in the high-mid;

The second is to note the chain head of the latter half chain.

/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {val = x; next = null;} *} *//** * Definition for Binary tree * public class TreeNode {* Int. val; * TreeNode left, * TreeNode right; * TreeN  Ode (int x) {val = x;} *} */public class Solution {public TreeNode Sortedlisttobst (ListNode head) {int len =        0;        ListNode p = head;            while (P! = null) {len++;        p = p.next;    } return Create (head,0,len-1);        Public TreeNode Create (ListNode head, Int. Low, int.) {if (Low > high) {return null;        } int mid = (low + high) >> 1;        int count = 0;        ListNode p = head;            while (Count < mid) {p = p.next;        count++;        } TreeNode t = new TreeNode (p.val);        T.left = Create (head,0,mid-1);        T.right = Create (p.next,0,high-mid-1);    return t; }} 

Runtime: 281 Ms

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.