题目链接:https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
方法一:
思路,先把链表转化为数组,然后利用108题的解法。
AC 1ms Java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head==null)
return null;
int len=0;
ListNode p=head;
while(p!=null){
p=p.next;
len++;
}
int[] nums = new int[len];
p=head;
int i=0;
while(p!=null){
nums[i]=p.val;
p=p.next;
i++;
}
TreeNode root=helper(nums,0,nums.length-1);
return root;
}
public TreeNode helper(int[] nums,int start,int end){
if(start>end)
return null;
int mid=(start+end)/2;
TreeNode root=new TreeNode(nums[mid]);
root.left=helper(nums,start,mid-1);
root.right=helper(nums,mid+1,end);
return root;
}
}
方法二:官方版
思路是利用二叉搜索树的性质,中序遍历的第一个节点恰好是链表的第一个节点。
AC :
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
ListNode node;
public TreeNode sortedListToBST(ListNode head) {
if(head==null)
return null;
ListNode p=head;
node=head;
int len=0;
while(p!=null){
len++;
p=p.next;
}
return helper(0,len-1);
}
public TreeNode helper(int start,int end){
if(start>end){
return null;
}
int mid=(start+end)/2;
TreeNode left=helper(start,mid-1);
TreeNode root=new TreeNode(node.val);
node=node.next;
root.left=left;
root.right=helper(mid+1,end);
return root;
}
}