109.Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
给定一个单元链表,元素按照升序排列,将其转换为高度平衡的BST。
平衡二叉查找树的特点是,除了满足BST的基本特点,另外对于任意一个结点,它左子树和右子树的深度最大差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; }
}
方法一:
利用LeetCode108:convertSortedArraytoBinarySearchTree先把链表转换成数组,然后采用相同的方法来做。
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
return helper(head, null);
}
private TreeNode helper(ListNode head, ListNode tail) {
if (head == tail) return null;
ListNode slow = head;
ListNode fast = head;
while (fast != tail && fast.next != tail) {
slow = slow.next;
fast = fast.next.next;
}
TreeNode root = new TreeNode(slow.val);
root.left= helper(head, slow);
root.right = helper(slow.next, tail);
return root;
}
}
方法二:
不需要将链表转换成数组,直接将链表转换成BST,方法思路和将数组装换成BST是一样的,链表有一个难点,就是找到链表的中间元素。
public TreeNode sortedListToRST2(ListNode head){
if(head == null) return null;
return sortedSubTree(head);
}
public TreeNode sortedSubTree(ListNode head){
if(head == null) return null;
if(head.next == null) return new TreeNode(head.val);
ListNode fast = head;
ListNode slow = head;
ListNode last = head;
//这里的while循环利用一个快指针一个慢指针,当快指针到达链表结束时,慢指针指向链表中间元素。
while(fast != null && fast.next != null){
fast = fast.next.next;
last = slow;
slow = slow.next;
}
//下面两条语句就将链表拆分成两条链表
ListNode right = slow.next;
last.next = null;
TreeNode root = new TreeNode(slow.val);
root.left = sortedSubTree(head);
root.right = sortedSubTree(right);
return root;
}
方法三:
跟上面的方法一样,只是将一条链表拆分成两条链表的方式不一样。
public TreeNode sortedListToBST3(ListNode head) {
if (head == null) return null;
return helper(head, null);
}
private TreeNode helper(ListNode head, ListNode tail) {
if (head == tail) return null;
ListNode slow = head;
ListNode fast = head;
while (fast != tail && fast.next != tail) {
slow = slow.next;
fast = fast.next.next;
}
TreeNode root = new TreeNode(slow.val);
root.left= helper(head, slow);
root.right = helper(slow.next, tail);
return root;
}