对于一个有序的数组要转化为二分查找树,实际上就是在找这个数组的中值,这个值之前的数是左子树,右边的数是右子树,可以递归的来做。。。。。(由二分查找树的性质决定)....这里我们要找到当前数组的中点并记录中点的前一点....
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head==null)
{
return null;
}
ListNode st = head.next;
ListNode mid = head;
ListNode preMid = null;
while(st!=null)
{
st = st.next;
if(st!=null)
{
st = st.next;
}
preMid = mid;
mid = mid.next;
}
TreeNode root = new TreeNode(mid.val);
if(preMid!=null)
{
preMid.next = null;
root.left = sortedListToBST(head);
}
root.right = sortedListToBST(mid.next);
return root;
}
}