LeetCode 109. Convert Sorted List to Binary Search Tree
题目来源:https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
思路1:将链表转化为数组后,再转化为二叉搜索树
public TreeNode sortedListToBST(ListNode head) {
if(head==null)
return null;
int len=0,i=0;
ListNode p=head;
while(p.next!=null){
len++;
p=p.next;
}
int a[]=new int[len];
while(head.next!=null){
a[i++]=head.val;
head=head.next;
}
TreeNode root=CreatBST(a, 0, len-1);
return root;
}
public TreeNode CreatBST(int []nums,int left,int right){
if(left>right)
return null;
int mid=(left+right)/2;
TreeNode node=new TreeNode(nums[mid]);
node.left=CreatBST(nums, left, mid-1);
node.right=CreatBST(nums, mid+1,right);
return node;
}
思路2:利用快慢指针,找到链表中点所在位置(经常用的一种方式),将每次二分查找得到的链表中点递归插入;
public TreeNode sortedListToBST(ListNode head) {
if(head==null)
return null;
return CreatBST(head,null);
}
public TreeNode CreatBST(ListNode head,ListNode tail){
ListNode slow=head;
ListNode fast=head;
if(head==tail)
return null; //不加这句话,产生栈溢出,如果没有返回空的语句,递归不会结束。
while(fast!=tail&&fast.next!=tail){
slow=slow.next;
fast=fast.next.next;
}
TreeNode root =new TreeNode(slow.val); //通过快慢指针的方式找到链表的中点slow
root.left=CreatBST(head, slow);
root.right=CreatBST(slow.next, tail);
return root;
}