Convert Sorted List to Binary Search Tree

2471 ワード

public class Solution {

    public TreeNode sortedListToBST(ListNode head) {

        if(head==null) return null;

        int len = 0;

        ListNode t = head;

        while(t!=null){

            len++;

            t = t.next;

        }

        if(len==1) return new TreeNode(head.val);

        return findRoot(0, len-1, head);

    }

    public TreeNode findRoot(int start, int end, ListNode n){

        if(start>end) return null;

        ListNode t = n;

        int mid = start +(end-start)/2;

        for(int i=start; i<mid; i++){

            t = t.next;

        }

        TreeNode root = new TreeNode(t.val);

        root.left = findRoot(start,mid-1, n);

        root.right = findRoot(mid+1,end,t.next);

        return root;

    }

}

にぶんほうたんさく