Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
Idea: The difference between this problem and the sorted array is that the list does not know the length and the value above. The overall idea is the middle value as the root node, but requires a little strategy, otherwise it will time out.
After the whole length is traversed, the length is saved so that you do not have to traverse the list every time.
The code is as follows:
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {val = x;} *} *//** * Definition fo R a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public TreeNode Sortedlisttobst (ListNode head) {/** * First calculates the overall length of the linked list * and then the median value, the median As the root node * The former linked list of the middle value is truncated as the left subtree * after the middle value of the linked list is truncated as the right subtree */int len = 0; ListNode p = head; while (head! = null) {head = Head.next; len++; } return BST (P,len); }/** * head node * len List length */private TreeNode BST (listnode head, int len) {if (len <= 0) { return null; } if (len = = 1) {return new TreeNode (Head.val); } int mid = 0; ListNode p = head; ListNode nexthead = null; Get middle value while (++mid < LEN/2) { p = p.next; } nexthead = p.next;//root node p.next = null; TreeNode root = new TreeNode (nexthead.val); Left and right sub-tree Root.left = BST (Head,mid); Root.right = BST (nexthead.next,len-mid-1); return root; } }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leecode 109.Convert Sorted List to Binary Search Tree (convert sorted list to BST) ideas and methods for solving problems