Iterative solution for building a BST from a sorted linked list

I want to create a BST from a sorted linked list. I solved the problem recursively, but wondered how to write an iterative solution for the same thing without changing the complexity of the problem.

[EDIT]

Note. I do not want to implement my own stack.

[EDIT2]

A function that calls itself recursively will be f. The pseudocode is given below. Call f with head pointer frommain

node * f(int start_index, int end_index, node *ptr) {
     if ( start>end) return NULL
     middle_index = start_index + (end_index-start_index)/2
     node *l_child = f(start_index, middle_index-1, ptr)
     initialize parent with ptr value 
     parent->left = l_child
     ptr = ptr->next
     parent->right = f(middle_index+1, end, ptr)
     return parent
}
+5
source share
2 answers

Assuming you want this to be so rude:

    _______
   /       \
  / \     / \
 /   \   /   \
/ \ / \ / \ /
1 2 3 4 5 6 7

. L < 2 N N , "null" (, , ), , (2 * 2 N) - 1. :

    12345678
   /       \
  1234    5678
  / \     / \
 12  34  56  78
/ \ / \ / \ / \
1 2 3 4 5 6 7

, , : - {1,2}->12, {3,4}->34, {12,34}->1234, .... - . , N (3) :

step 1:    1  2   3  4    5  6   7
step 2:   (1  2) (3  4)  (5  6) (7   )
step 3:  ((1  2) (3  4))((5  6) (7   ))
step 4: (((1  2) (3  4))((5  6) (7   )))

.

- . 7 : {1,2}, {3,4}, {5,6}, {7,null}, {12,34}, {56,78}, {1234,5678}. , , : 9={1,2}, 10={3,4}, 11={5,6}, 12={7,null}, 13={9,10}, 14={11,12}, 15={13,14}. , , . .

0

"" .

-1

All Articles