/*
Key to solve: DFS
1.find length of LinkedList
2. Need to set the mid point of Linkedlist as root in order to construct Binary Search Tree
3.recursively construct left sub tree from start to mid-1 (left portion of Linkedlist)
4.recursively construct right sub tree from mid+1 to end ((right portion of Linkedlist))
*/
public class Solution {
private ListNode headGlobal;
public TreeNode sortedListToBST(ListNode head) {
headGlobal = head;
ListNode temp = head;
int length = 0;
while (temp != null) {
length++;
temp = temp.next;
}
return helperDFS(0, length - 1);
}
private TreeNode helperDFS(int begin, int end) {
if (begin > end) return null;
int mid = (begin + end) / 2;
//reverse point mid point for root
TreeNode left = helperDFS(begin, mid - 1);
TreeNode root = new TreeNode(headGlobal.val);
headGlobal = headGlobal.next;
TreeNode right = helperDFS(mid + 1, end);
root.left = left;
root.right = right;
return root;
}
}
Convert Sorted List to Binary Search Tree Java
最新推荐文章于 2020-08-16 16:12:05 发布