[Leedcode 109] 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.

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*//*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode Sortedlisttobst (ListNode head) {if(head==NULL)return NULL; intLen=0; ListNode node=Head;  while(node!=NULL) {node=Node.next; Len++; }        returnGetbst (head,0,len-1); } TreeNode Getbst (ListNode head,intStartintend) {        if(Start>end)return NULL; intMid= (start+end)/2; ListNode Temp=Head;  for(inti=start;i<mid;i++) {//Finding the middle node method ———— start to midtemp=Temp.next; } TreeNode Node=NewTreeNode (Temp.val); Node.left=getbst (head,start,mid-1); Node.right=getbst (Temp.next,mid+1,end);//note the head node of the list of nodes on the right!!! Because the array is not the same way to find the middle node, the list is mainly to traverse, to find the relative position        returnnode; }}

[Leedcode 109] 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.