java - BST List from a sorted Array -
this question lab , stumped. array sorted, , have use array create bst in list format. (how like)? here code have far, doesn't work @ , don't know how fix it:
private static void buildbalancedrec(integer [] temparr, int start, int end, binarysearchtreelist<integer> bstlist) { if (bstlist.size()<temparr.length){ integer middle = temparr[(start+end)/2]; bstlist.add(middle); buildbalancedrec(temparr, start , middle-1 , bstlist); buildbalancedrec(temparr, middle+1, end, bstlist); }
assuming array {1,2,3,4,5,6,7}. start 1, , end 7. assuming bst list supposed like: {4, 2, 6, 1, 3, 5, 7}, correct? bst like:
4 / \ 2 6 /\ /\ 1 3 5 7
so assumed list that.
how there? , can have 2 lines back-to-back recursion have in current code?
i tried many ways, can never print {4, 2, 6, 1, 3, 5, 7}.
any guidance appreciated!
note: method needs use recursion
try with:
private static void buildbalancedrec(int[] temparr, int start, int end, binarysearchtreelist<integer> list) { if (start < end) { int middle = (start + end) / 2; list.add(temparr[middle]); buildbalancedrec(temparr, start, middle, list); buildbalancedrec(temparr, middle + 1, end, list); } }
edit:
full example:
private static void buildbalancedrec(int[] temparr, int start, int end, list<integer> list) { if (start < end) { int middle = (start + end) / 2; list.add(temparr[middle]); buildbalancedrec(temparr, start, middle, list); buildbalancedrec(temparr, middle + 1, end, list); } } public static void main(string[] args) { int[] temparr = {1, 2, 3, 4, 5, 6, 7}; list<integer> list =new arraylist<>(temparr.length); buildbalancedrec(temparr, 0, temparr.length, list); system.out.println(list); }
it prints:
[4, 2, 1, 3, 6, 5, 7]
Comments
Post a Comment