This is No.109 in leetcode.
Below is the solution:
/**
* 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; } }
*/
class Solution {
private ListNode findMiddleElement(ListNode head) {
// The pointer used to disconnect the left half from the mid node.
ListNode prevPtr = null;
ListNode slowPtr = head;
ListNode fastPtr = head;
// Iterate until fastPr doesn't reach the end of the linked list.
while (fastPtr != null && fastPtr.next != null) {
prevPtr = slowPtr;
slowPtr = slowPtr.next;
fastPtr = fastPtr.next.next;
}
// Handling the case when slowPtr was equal to head.
if (prevPtr != null) {
prevPtr.next = null;
}
return slowPtr;
}
public TreeNode sortedListToBST(ListNode head) {
// If the head doesn't exist, then the linked list is empty
if (head == null) {
return null;
}
// Find the middle element for the list.
ListNode mid = this.findMiddleElement(head);
// The mid becomes the root of the BST.
TreeNode node = new TreeNode(mid.val);
// Base case when there is just one element in the linked list
if (head == mid) {
return node;
}
// Recursively form balanced BSTs using the left and right halves of the original list.
node.left = this.sortedListToBST(head);
node.right = this.sortedListToBST(mid.next);
return node;
}
}
To solve this problem, I think here are some points I should remember:
- How to get the middle node of a linked list?
Use the slow&fast points. The slow node move one node in a time, and the fast node move two nodes in a time. The final slow node will be the middle one. - What it the height of BST?
The height of a binary tree is the number of edges between the tree’s root and its furthest leaf. - How to cur off the left halve of linked list?
Use another node and set the next to null.