标签:
给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二分查找树
找到中间点,建立树的根结点 
左右半边递归 
注意: 
右半边链表可以根据找到的中间节点进行递归 
左半边要找到结束位置,这里我新建了一个链表
/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: a tree node
     */
    public TreeNode sortedListToBST(ListNode head) {  
        // write your code here
        ListNode p1 = head;
        ListNode mid = findMiddle(p1);
        if(mid==null)
            return null;
        TreeNode root = new TreeNode(mid.val);
        // 右边递归
        TreeNode right = sortedListToBST(mid.next);
        if(right!=null)
            root.right = right;
        // 找到left半边
        ListNode leftHead = new ListNode(-1);
        ListNode leftList = leftHead;
        while(head!=null && head!=mid){
            leftList.next = head;
            leftList = leftList.next;
            head = head.next;
        }
        leftList.next = null;
        // 左边递归
        TreeNode left = sortedListToBST(leftHead.next);
        if(left!=null)
            root.left = left;
        return root;
    }
    // 找到中间节点
    public ListNode findMiddle(ListNode head){
        if(head==null || head.next==null){
            return head;
        }
        ListNode slow = head;
        ListNode fast = head;
        while(fast!=null && fast.next!=null && fast.next.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}
标签:
原文地址:http://blog.csdn.net/qunxingvip/article/details/51886364