Given a singly linked list where elements is sorted in ascending order, convert it to a height balanced BST.
Original title Link: https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
Title: Given a list with a positive sequence, convert it into a binary search tree.
Idea: able to follow the previous array of ideas to do. The middle value is found. Again left and right recursive achievements.
Public TreeNode Sortedlisttobst (ListNode head) {if (head = = null) return null;int len = 0; ListNode tmp = Head;while (tmp! = NULL) {TMP = tmp.next;len++;} Return Sortedlisttobst (head, Len);} Public TreeNode Sortedlisttobst (listnode head, int len) {if (len <= 0) return null;int mid = (1 + len)/2; ListNode p = head;int tmp = mid-1;while (tmp > 0) {p = p.next;tmp--;} TreeNode root = new TreeNode (p.val); root.left = Sortedlisttobst (head, mid-1); root.right = Sortedlisttobst (P.next, Len- mid); return root;} Definition for singly-linked List.public class ListNode {int val; ListNode Next; ListNode (int x) {val = X;next = null;}} Definition for binary Treepublic class TreeNode {int val; TreeNode left; TreeNode right; TreeNode (int x) {val = x;}}
Leetcode--convert Sorted List to Binary Search Tree