Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
思路:找到中间节点,中间节点是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; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head)
{
int nlen = 0,i=0;
ListNode p =head;
while(p!=null)
{
nlen++;
p=p.next;
}
if(nlen==0)
return null;
int[] num = new int[nlen];
while(head!=null)
{
num[i++]=head.val;
head=head.next;
}
int mid = nlen/2;
TreeNode root = new TreeNode(num[mid]);
helper(num,0,mid-1,root,0);
helper(num,mid+1,nlen-1,root,1);
return root;
}
public void helper(int[] num,int i,int j,TreeNode cur,int flag)
{
if(i<=j)
{
int l = i, r = j;
int mid = l+(r-l)/2;
TreeNode tn = new TreeNode(num[mid]);
if(flag==0) // left
{
cur.left=tn;
helper(num,l,mid-1,tn,0);
helper(num,mid+1,r,tn,1);
}
if(flag==1) // right
{
cur.right=tn;
helper(num,l,mid-1,tn,0);
helper(num,mid+1,r,tn,1);
}
}
}
}