The problem with the function is that after 1 calling of it, it doesn't work as it should. For example, for k = 4, and size of a tree n = 7, when called it should return firstly node with value of 4 then 5, when in reality it return node with value 4 and NULL pointer. Can not find solution for that.
I've been struggling with this function for quite some time, It takes node_t *root as a root of our tree and k as a k'th element. Our structure looks like it.
typedef struct node_t{
struct node_t *left, *right, *up;
node *key; // its just a node from linked list from which tree was created, so key -> value
bool isVisited;
int t; // number of subnodes + 1
}
our function should also decrease t on every node from root to designated node and change isVisited to true, so we don't visit it again.
node_t *nextK(node_t *root, int k){
int leftSize = 0;
if(root == NULL) return NULL;
if(root -> left != NULL){
leftSize = root -> left -> t;
}
if(k <= leftSize) {
root -> t = root -> t - 1;
return nextK(root -> left, k);
}
if(k == leftSize + 1 && root -> isVisited == false) {
root -> isVisited = true;
return root;
}
else{
root -> t = root -> t - 1;
return nextK(root -> right, k - leftSize);
}
}
Example how our BCT is created from linked_list:
node_t *linkedListToBST(node *linked_list, node_t *root, node_t *temp){
if(linked_list!=NULL) {
node_t *new;
new = malloc(sizeof(node_t));
new -> isVisited = false;
new -> up = root;
new -> key = middle(linked_list);
new -> right=linkedListToBST(new -> key -> next, new, temp);
if(new-> key!=linked_list)
new-> left= linkedListToBST(linked_list, new, temp);
else{
new-> left= linkedListToBST(NULL, new, temp);
}
new -> t= new -> right -> t + new -> left -> t +1;
return new;
}
else{
return temp;
}
}
node_t *iniBST2(node_t *root, node *head){
node_t sentinel;
sentinel.t = 0;
sentinel.left = &sentinel;
sentinel.right = &sentinel;
sentinel.up = &sentinel;
node_t *new_root;
new_root = linkedListToBST(head, root, &sentinel);
return new_root;
}
void addFirst(node **head, int v) {
node *new_head;
new_head = malloc(sizeof(node));
new_head->value = v;
new_head->next = *head;
*head = new_head;
}
int n = 7;
for(int i = n; i > 0; i--){
addFirst(&linked_list, i);
if(i == n){
tail = linked_list;
}
}