/**
* Definition for singly-linked list
*/
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
/**
* Definition for a binary tree node.*/
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
int end = 0;
ListNode p = head;
while(p!=null) {
p = p.next;
end++;
}
return helper(head, 0, end-1);
}
//start sis the start node of the list, end is (the index of end node of the list)
public TreeNode helper(ListNode head, int start, int end) {
if(end - start < 0 || head == null) return null;
int mid = start + (end - start)/2;
ListNode p = head;
for(int i = 0; i < (mid-start); i++)
p = p.next;
TreeNode root = new TreeNode(p.val);
root.left = helper(head, start, mid-1);
root.right = helper(p.next, mid+1, end);
return root;
}
public static void main(String[] args) {
Solution a = new Solution();
a.sortedListToBST(new ListNode(0));
}
}
bst
最新推荐文章于 2020-10-09 15:27:53 发布