Easy Java solution

  • 4
    public TreeNode sortedListToBST(ListNode head) {
        HashMap<Integer,TreeNode> map = new HashMap<Integer,TreeNode>();
    	ListNode p ;
    	int i = 0;
    	for(p=head ; p!=null ; p = p.next){
    		map.put(i, new TreeNode(p.val));
    	return buildTree(map,0,i-1);
    public static TreeNode buildTree(HashMap<Integer,TreeNode> map, int start , int end){
    		int mid = (start+end)/2;
    		TreeNode t = map.get(mid);
    		t.left = buildTree(map,start,mid-1);
    		t.right = buildTree(map,mid+1,end);
    		return t;
    	else return null;

  • 1

    if the purpose of using map is to locate something in constant time, why not try arraylist? or simple array?

  • 0

    Brilliant idea. And I also don't why I use hashmap when I solved this problem.... Thank you.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.