LeetCode 109 - Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

private ListNode h;
public TreeNode sortedListToBST(ListNode head) {
    if(head == null) return null;
    h = head;
    
    int len = 1;
    ListNode node = head;
    while((node=node.next)!=null) len++;
    
    return toBST(0, len-1);
}

public TreeNode toBST(int start, int end) {
    if(start > end) return null;
    int m = (start+end)>>1;
    TreeNode left = toBST(start, m-1);
    TreeNode root = new TreeNode(h.val);
    h = h.next;
    TreeNode right = toBST(m+1, end);
    root.left = left;
    root.right = right;
    return root;
}

 

你可能感兴趣的:(BST)