Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* 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 {
public TreeNode sortedListToBST(ListNode head) {
List<Integer> arr = convertListToArray(head);
return getBInaryTree(arr, 0 , arr.size() -1);
}
private List<Integer> convertListToArray(ListNode head){
List<Integer> arr = new ArrayList<Integer>();
while(head != null){
arr.add(head.val);
head = head.next;
}
return arr;
}
private TreeNode getBInaryTree(List<Integer> arr, int start, int end){
if(start > end){
return null;
}
int mid = (start + end) / 2;
TreeNode node = new TreeNode(arr.get(mid));
node.left = getBInaryTree(arr, start, mid - 1);
node.right = getBInaryTree(arr, mid + 1 , end);
return node;
}
}
/**
* 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 {
public TreeNode sortedListToBST(ListNode head) {
List<Integer> arr = convertListToArray(head);
return getBInaryTree(arr, 0 , arr.size() -1);
}
private List<Integer> convertListToArray(ListNode head){
List<Integer> arr = new ArrayList<Integer>();
while(head != null){
arr.add(head.val);
head = head.next;
}
return arr;
}
private TreeNode getBInaryTree(List<Integer> arr, int start, int end){
if(start > end){
return null;
}
int mid = (start + end) / 2;
TreeNode node = new TreeNode(arr.get(mid));
node.left = getBInaryTree(arr, start, mid - 1);
node.right = getBInaryTree(arr, mid + 1 , end);
return node;
}
}
No comments:
Post a Comment