Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST
=================
Analysis:
Rules of height balanced BST:
1. all node values in left subtree less than value of current node
2. all node values in right subtree less than value of current node
3. heigh difference no more than 1
In this problem, we are given a sorted linked list, which can be transformed to a sorted array list. Then the problem can be simplified to construct a height balanced BST from sorted numbers.
Obviously, we can use recursive approach. Each recursive call construct one tree node. Therefore, in each recursive call:
1. set value of current node as the middle element of the given array (according to rule1&2, value of current node should be value of the middle element of the given array)
2. set left subtree by recursive call with left->middle-1 array elements
3. set right subtree by recursive call with middle+1->right array elements
exist: left>right
/**
* 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;
ArrayList<Integer> listNode = new ArrayList<Integer>();
while(head != null){
listNode.add(head.val);
head = head.next;
}
int left = 0;
int right= listNode.size()-1;
return helper(listNode, left, right);
}
public TreeNode helper(ArrayList<Integer> listNode, int left, int right){
if(left>right) return null;
TreeNode node = new TreeNode(0);
int mid = (left+right)/2;
node.val = listNode.get(mid);
node.left = helper(listNode, left, mid-1);
node.right = helper(listNode, mid+1, right);
return node;
}
}