java - making a Binary Search Tree from a Sorted Doubly Linked List -
hey guys studying programming interview questions , got stuck in one.
i trying recursively don't know start.
this algorithm have far:
maketree(head, tail){ nodemid = list/2 root = nodemid root.left = maketree(head, nodemid) root.right = maketree(nodemid, tail)
do have right idea? input highly appreciated. thanks!
the major problem see , forgive me if wrong not changing location of list each node. each time recursively call
maketree(head, tail){ nodemid = list/2;
as far can see inside loop not change part of list goes recursive call. ie have array of ints myints has (0,1,2,3,4,5,6,7,8,9) every time recursion called infinitely fill binary tree number @ list/2 need change value of nodemid each call, use head/tail variables sending.
you not want keep resetting root node either. should using "this" operator set value of current node looking at.
start being start of portion of array looking @ , end being end of portion. recursive calls so. need add in boundaries of recursion
using bst nodes when create new node in tree left , right nodes set null start with. need create new node , call recursion.
node maketree(int head, int tail){ nodemid = (head+tail)/2; = new node(); if(head < nodemid-1) { this.left = maketree(head, nodemid-1); } if(nodemid < tail) { this.right = maketree(nodemid, tail); } this.setvalue(list[nodemid]); return this; }
after recursion done need set value of current node , return node creation. recursively turn sorted array binary search tree. put in proper list coding doubly linked list.
to start recursion
root = maketree(0, list.length());
Comments
Post a Comment