Convert Sorted List to Balanced BST(排序列表转换为二分查找树)

http://www.lintcode.com/en/problem/convert-sorted-list-to-balanced-bst/?rand=true

/**
 * 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 {
    private ListNode current;

    /*
     * @param head: The first node of linked list.
     * @return: a tree node
     */
    public TreeNode sortedListToBST(ListNode head) {
        // write your code here
        if (head == null) {
            return null;
        }
        current = head;
        int len = getNodeLength(head);
        //使用递归去生成树,中间节点是根节点,左边是左节点,右边是右节点。
        return tree(len);

    }

    private TreeNode tree(int len) {
        if (len <= 0) {
            return null;
        }
        TreeNode left = tree(len / 2);
        TreeNode node = new TreeNode(current.val);
        //这个是非常巧妙,一定要注意是先left后node最后right,
        // 这样current一直向后偏移,一直是升序,
        current = current.next;
        TreeNode right = tree(len - 1 - len / 2);
        node.left = left;
        node.right = right;
        return node;
    }

    private int getNodeLength(ListNode head) {
        int i = 0;
        while (head != null) {
            i++;
            head = head.next;
        }
        return i;
    }
}

你可能感兴趣的:(Convert Sorted List to Balanced BST(排序列表转换为二分查找树))