Easy Java solution


  • 4
    G
    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));
    		i++;
    	}
    	return buildTree(map,0,i-1);
    }
    
    
    public static TreeNode buildTree(HashMap<Integer,TreeNode> map, int start , int end){
    	if(start<=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
    Z

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


  • 0
    G

    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.