题目描述:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路解析:
自顶向下建树:
- 先用快慢指针找到链表的中间节点,然后把它设置为树的根节点。
- 在找的过程中,注意的是把中间节点的前一个节点也找到,这样就可以断开前后了。
- 然后递归左链表,右链表,分别是左子数的根节点,右子树的根节点。
public class Solution {//二分查找树:左子树都比根节点小,右子树都比根节点大
public TreeNode sortedListToBST(ListNode head) {
if(head==null)
return null;
if(head.next ==null){
return new TreeNode(head.val);
}
ListNode fast = head;
ListNode slow = head;
ListNode premid = null;
/*注意这里不写fast.next!=null&&fast.next.next!=null
*1->2->3->4->null这个链表中间节点是3
*/
while(fast!=null&&fast.next!=null){
premid = slow;
slow = slow.next;
fast = fast.next.next;
}
TreeNode root = new TreeNode(slow.val);
premid.next = null;
root.left = sortedListToBST(head);
root.right = sortedListToBST(slow.next);
return root;
}
}