题目:Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:
链接:https://www.nowcoder.net/questionTerminal/86343165c18a4069ab0ab30c32b1afd0
二分查找法每次需要找到中点,而链表的查找中间点可以通过快慢指针来操作。找到中点后,要以中点的值建立一个数的根节点,然后需要把原链表断开,分为前后两个链表,都不能包含原中节点,然后再分别对这两个链表递归调用原函数,分别连上左右子节点即可。
注意:BST是二叉排序树,左子树的值小于根节点小于右子树的值。
代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; next = null; } * } */ /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode sortedListToBST(ListNode head) { if(head == null){ return null; } if(head.next == null){ return new TreeNode(head.val); } ListNode slow = head; ListNode fast = head.next; while(fast.next != null && fast.next.next != null){ slow =slow.next; fast = fast.next.next; } TreeNode root = new TreeNode(slow.next.val); root.right = sortedListToBST(slow.next.next); slow.next = null; root.left = sortedListToBST(head); return root; } }