[leedcode 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.

/**
 * 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) {
        if(head==null) return null;
        int len=0;
        ListNode node=head;
        while(node!=null){
            node=node.next;
            len++;
        }
        return getBST(head,0,len-1);
    }
    TreeNode getBST(ListNode head,int start,int end){
        if(start>end) return null;
        int mid=(start+end)/2;
        ListNode temp=head;
        for(int i=start;i<mid;i++){//求中间节点方法————start到mid
            temp=temp.next;
        }
        TreeNode node=new TreeNode(temp.val);
        node.left=getBST(head,start,mid-1);
        node.right=getBST(temp.next,mid+1,end);//注意右侧节点链表的头结点!!!因为和数组求中间节点的方式不一样,链表主要是遍历,求相对位置
        return node;
    }
}

 

你可能感兴趣的:(Binary search)