106. 有序链表转换为二叉搜索树
给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二叉搜索树
样例
样例 1:
输入: array = 1->2->3
输出:
2
/ \
1 3
样例 2:
输入: 2->3->6->7
输出:
3
/ \
2 6
\
7
解释:
可能会有多个符合要求的结果,返回任意一个即可。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param head: The first node of linked list.
* @return: a tree node
*/
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
ListNode next = head;
int i = 0;
while (next != null) {
i++;
next = next.next;
}
return help(head, i - 1);
}
private TreeNode help(ListNode head, int i) {
if (i <0) return null;
if (i == 0) return new TreeNode(head.val);
int mid = i / 2;
int temp = mid;
ListNode low = head;
while (temp > 0) {
temp--;
low = low.next;
}
TreeNode root = new TreeNode(low.val);
root.left = help(head, mid-1);
root.right = help(low.next, i-mid-1);
return root;
}
}
public TreeNode sortedListToBST(ListNode head) {
if(head==null)return null;
ListNode next=head;
int i=0;
while (next!=null){
i++;
next=next.next;
}
return help(head,0,i-1);
}
private TreeNode help(ListNode head , int start, int end) {
if (end<start)return null;
int mid = (end + start) / 2;
TreeNode root = new TreeNode(getMid(head,mid));
root.left = help(head,start,mid-1);
root.right = help(head,mid+1,end);
return root;
}
private int getMid(ListNode head, int i) {
while (i>0){
i--;
head=head.next;
}
return head.val;
}
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param head: The first node of linked list.
* @return: a tree node
*/
public TreeNode sortedListToBST(ListNode head) {
if(head==null)return null;
int[] nums=new int[1000000];
int i=0;
while (head!=null){
nums[i]=head.val;
i++;
head=head.next;
}
return help(nums,0,i-1);
}
private TreeNode help(int[] nums, int start, int end) {
if (end<start)return null;
int mid = (end + start) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = help(nums,start,mid-1);
root.right = help(nums,mid+1,end);
return root;
}
}