Description:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
问题描述:
给一条已经排好序的单链表(元素次序按升序排列),将其转化为等价的二叉搜索树(Binary Search Tree ).
二叉搜索树:
这里要明白二叉搜索树的几点性质:
+ 任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
+ 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
+ 任意节点的左、右子树也分别为二叉查找树;
+ 没有键值相等的节点。
解法一:
思路:
这道题的关键步骤之一是要找到中间结点的位置,所以需要在循环中使用快慢指针。不过为了准确地将快指针定位到末尾结点,这里将快指针的两步分开写,并且在第一步到达链表末尾时便退出循环,慢指针最后定位到链表的中间结点,prev指针记录慢指针上一次的位置。循环退出后,将以中间结点的两部分切分。
构造BST的关键步骤–将中间结点的值(慢指针所指)赋给BST的根结点,递归构造BST(前半部分的头结点(head)赋给左子树,后半部分的头结点(slow.next)赋给右子树),最后返回BST的跟结点。
Code:
/**
* 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; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
//base case
if(head == null) return null;
ListNode slow = head;
ListNode fast = head;
ListNode prev = null;
//find the midian node in the linked list , after executing this loop
//fast will point to the last node , while slow is the median node
while(fast.next != null){
fast = fast.next;
if(fast.next == null){
break;
}
fast = fast.next;
prev = slow;
slow = slow.next;
}
if(prev != null) prev.next = null;
else head = null;
TreeNode root = new TreeNode(slow.val);
root.left = sortedListToBST(head);
root.right = sortedListToBST(slow.next);
return root;
}
}