/**
* 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;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
//ArrayList<Integer> a = new ArrayList<Integer>();
if(head==null)return null;
int count = 0;
int i = 0;
ListNode t = head;
while(t!=null){
count++;t = t.next;
}
t = head;
int[] num = new int[count];
while(t!=null){
num[i++] = t.val;
t = t.next;
}
return mid(num,0,count-1);
}
private TreeNode mid(int[] num,int begin,int end){
if(begin==end){
return new TreeNode(num[begin]);
}
else{
int cur = begin+(end+1-begin)/2;
TreeNode t = new TreeNode(num[cur]);
t.left = mid(num,begin,cur-1);
if(cur!=end)t.right = mid(num,cur+1,end);
return t;
}
}
}
這個題有點偷懶了
Convert Sorted List to Binary Search Tree
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.