1 解题思想
这道题,完全就是108的升级,108是数组,109难一些,是链表
Leetcode 108. Convert Sorted Array to Binary Search Tree 有序数组转化BST 解题报告
这道题的核心idea是使用快慢指针,找到中间位置后把他当做当前的Root,再递归构建左右两边
2 原题
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
3 AC解
/**
* 每次都找到当前部分链表的中间位置,将他作为头结点,然后将之前的和之后的重新作为一个子问题,找到其中间位置作为各自的子节点,这样递归下去就可以
*
* */
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
return toBST(head,null);
}
public TreeNode toBST(ListNode head,ListNode tail){
if(head == tail) return null;
ListNode slower = head;
ListNode faster = head;
while(faster!=tail){
faster = faster.next;
if(faster!=tail){
faster = faster.next;
slower = slower.next;
}
}
TreeNode root = new TreeNode(slower.val);
root.left = toBST(head,slower);
root.right = toBST(slower.next,tail);
return root;
}
}