方法一:
思路类似 LeetCode 108
也是每次加入中间元素;
只是改成了链表,不能随机存取;
使用快慢指针找到链表的中间结点;
递归构造平衡BST
注意点:
要添加终止条件: if(head == mid) return root;
如果不添加这个条件,当链表只有一个结点时,将无限循环递归(原因时在递归时传入的参数head 始终不改变,执行结果一样)
/**
* 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;
ListNode mid = findMidNode(head);
TreeNode root = new TreeNode(mid.val);
//如果不添加这个条件,当链表只有一个结点时,将无限循环递归(原因时在递归时传入的参数head 始终不改变,执行结果一样)
if(head == mid) return root;
root.left = sortedListToBST(head);
root.right = sortedListToBST(mid.next);
return root;
}
public ListNode findMidNode(ListNode head){
//if(head == null ) return null;
ListNode pre = null,slowPtr = head,fastPtr = head;
while(fastPtr!=null && fastPtr.next !=null){
pre = slowPtr;
slowPtr = slowPtr.next;
fastPtr = fastPtr.next.next;
}
if(pre!=null)
pre.next = null;
return slowPtr;
}
}
方法二:
思路:将有序链表转换成对应的数组,使之可以随机存取;然后方法同LeetCode 108
/**
* 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 {
private List<Integer> values = new ArrayList<Integer>();
public void ListToArray(ListNode head){
ListNode p = head;
while(p != null){
values.add(p.val);
p = p.next;
}
}
public TreeNode creatBST(int p, int q){
if(p>q)return null;
int mid = (p+q)/2;
TreeNode root = new TreeNode(values.get(mid));
root.left = creatBST(p,mid-1);
root.right = creatBST(mid+1,q);
return root;
}
public TreeNode sortedListToBST(ListNode head) {
ListToArray(head);
return creatBST(0,values.size()-1);
}
}
方法三:
模拟中序遍历(重点)
/**
* 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 {
private ListNode cur;
public int ListSize(ListNode head){
ListNode p = head;
int cnt = 0;
while(p != null){
cnt++;
p = p.next;
}
return cnt;
}
public TreeNode creatBST(int p, int q){
if(p>q)return null;
int mid = (p+q)/2;
TreeNode left = creatBST(p,mid-1);
TreeNode root = new TreeNode(cur.val);
cur = cur.next;
root.left = left;
root.right = creatBST(mid+1,q);
return root;
}
public TreeNode sortedListToBST(ListNode head) {
int size = ListSize(head);
this.cur = head;
return creatBST(0,size-1);
}
}