binary search tree print function: Logic not clear-help

Hello. Pls explain to me

1) how come root node is printed when the first call to function goes to left subtree?

2) How it resets to root to go to right subtree from last left tree leaf?

1
2
3
4
5
6
7
8
9
10
11
void bst:: printNodes(hwareItem*& root){

    if(root){
        printNodes(root->left);
        cout<<root->barcode<<endl;
        cout<<root->description<<endl;
        cout<<root->price_per_unit<<endl;
        cout<<root->stock<<endl;
        printNodes(root->right);}

}
I don't get you. This uses recursion(calling a function from itself)

Aceix.
Last edited on
The code looks fine to me. If the results aren't what you expect then maybe the structure of the tree isn't what you think?

2) How it resets to root to go to right subtree from last left tree leaf?

The beauty of recursion is that each call has different parameters (and local variables). So you don't need to "reset to root": when you return from a lower call, the previous value of root is there unchanged. Actually, to express this better in your code, don't make root a reference, and call it subtree:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void bst:: printNodes(hwareItem* subtree){

    if(subtree){
        printNodes(subtree->left);

        cout<< subtree->barcode << '\n';
        cout<< subtree->description << '\n';
        cout<< subtree->price_per_unit<< '\n';
        cout<< subtree->stock <<endl;

        printNodes(subtree->right);
   }

}


I've also replaced all but the last endl with '\n'. This will speed up the output y not flushing so frequently.
thanks...So it is ok to say variables are not replaced for each call? But is stored in stack all the updates?
That's right. When you call a function, the program allocates space on the stack for the parameters and local variables. This happens even when you make a recursive call: so each call has it's own set of local variables and parameters. In practice the compiler can sometimes optimize some of this away - such as by storing parameters in CPU registers instead of the stack, but think of that as an optimization - conceptually it's new space for each call.
Thanks...I will get back if I need help... :)
Last edited on
Why is that if I want to delete a node in single linked list I have to do it from head? I had two nodes in a list. I could delete head but to delete tail I had to copy tail to head and head to tail and then delete head so remove tail data from before...Why is that?

Last edited on
Why is that if I want to delete a node in single linked list I have to do it from head?
You don't have to, you can delete from anywhere in the list, but you have to make sure that the link that pointed to the item you delete, points to the next one on in the chain.

I had two nodes in a list. I could delete head but to delete tail I had to copy tail to head and head to tail and then delete head so remove tail data from before...Why is that?
That's all very confusing, you're looking at it the wrong way.

Draw out the linked list on paper, and it'll be obvious what needs to be done.
http://computer.howstuffworks.com/c32.htm
How could I write the removeNode code shorter?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
int linkedlist:: remNode(trans*& head, char inv[]){

    trans *prev, *curr, *tmp;

    if (head==NULL){
        cout<<"Nothing to remove in the list"<<endl;
        return -1;
    }
    else{
        curr=head;
        prev=head;
        while(curr!=NULL){

            if(curr==head){

                if(strcmp(inv, curr->inv_num)==0){

                    head=curr->next;
                    strcpy(head->hware_item_bar, curr->next->hware_item_bar);
                    strcpy(head->inv_num, curr->next->inv_num);
                    head->qt_pchase=curr->next->qt_pchase;
                    head->total_price=curr->next->total_price;
                    delete curr;

                    return 0;
                    }
                else
                    return -1;
                }
            else if (head->next->next==NULL){


                if(strcmp(inv,head->next->inv_num)==0){


                    curr=head->next;
                    strcpy(curr->hware_item_bar, head->hware_item_bar);
                    strcpy(curr->inv_num, head->inv_num);
                    curr->qt_pchase=head->qt_pchase;
                    curr->total_price=head->total_price;

                    delete head;
                    head=curr;;

                    strcpy(head->hware_item_bar, curr->hware_item_bar);
                    strcpy(head->inv_num, curr->inv_num);
                    head->qt_pchase=curr->qt_pchase;
                    head->total_price=curr->total_price;

                    return 0;

                        }
                else
                    return -1;

            }

            else if(curr){
                if(strcmp(inv,curr->inv_num)==0){

                    prev->next=curr->next;

                    strcpy(prev->next->hware_item_bar, curr->next->hware_item_bar);
                    strcpy(prev->next->inv_num, curr->next->inv_num);
                    prev->next->qt_pchase=curr->next->qt_pchase;
                    prev->next->total_price=curr->next->total_price;

                    delete curr;

                    return 0;


                }

                else
                    return -1;

            }

                prev=curr;
                curr=curr->next;

        }

    }

}
You shouldn't be copying things, once you've found the node, delete it.

1. Move the string compare as the top level test inside the loop, as that's what you really care about.
2. You're deleting a node, so I don't know why you're copying things--I removed all that code
3. Make the function return the number of entries deleted.
4. Remove redundant if then/else clauses.
5. Move variable declarations to where they're used.
6. curr becomes invalid after it's deleted, so reset it after deletion.
7. Add const to the string parameter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
int linkedlist::remNode(trans*& head, const char inv[]) {
	int count = 0;

	trans *curr = head;
	trans *prev = head;
	while (curr != NULL) {
		if (strcmp(inv, curr->inv_num) == 0) {
			if (curr == head) {
				trans* tmp = head;

				head = head->next;
				prev = head;

				delete tmp;
			}
			else {
				trans* tmp = curr;

				prev->next = curr->next;

				delete tmp;
			}

			curr = prev->next
			++count;
		}
		else {
			curr = curr->next;
		}
	}

	return count;
}
Last edited on
Thanks :). I have one more question

Please tell me what am I doing wrong. I wish to add a node in a certain position..say it is before position where value is 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
int patients:: addPatientEmg(patient*& head, ptient ptn){

    patient *curr, *prev, *tmp;


    if(head==NULL){
        addPatient(head,ptn);
        return 0;}
    else{

        curr=head;


        while(curr->next!=NULL){
            prev=curr;

            if(curr->next->priority==0){
                tmp=new patient;
                strcpy(tmp->name, ptn.name);
                tmp->priority=ptn.prio;

                prev->next=tmp;
                tmp->next=curr->next;

                break;


            }


            curr->next=curr->next->next;
        }


    }
    return 0;

}
Last edited on
You first have to find the value that has zero:
1
2
3
4
5
6
7
8
9
	trans *curr = head;
	while (curr != NULL) {
		if (curr->priority == 0) {
			// do the insert here
			break;
		}

		curr = curr->next;
	}


Then you do the insert:
1
2
3
4
5
6
7
8
			// create a new node
			trans* p = new trans;
			p->priority = ptn.prio;
			strncpy(p->name, ptn.name, sizeof(p->name) - 1);

			// insert it into the linked list
			p->next = curr->next;
			curr->next = p;
Last edited on
I did like this above, but I know I am wrong, but whats the logic error, I cant seem to visualise...
I posted a link earlier that has good diagrams and accompanied by a good explanation. Did you look at it?
Would it be possible to give something in C++ picture format?
You obviously didn't read the link; maybe someone else can help.
I did..Its in C but any way I will try to learn the C malloc syntax...thanks though
Last edited on
The data structures are same in C as it is in C++.

The point is memory is take of a heap and used in some structure. That link explains the who thing; from the rationale of using pointers to useful data strucutres.
Here is another site that has pictures of a linked list:
http://www.cs.usfca.edu/~srollins/courses/cs112-f07/web/notes/linkedlists.html

The algorithm to insert into a sorted list is:
if the list is empty or the new item goes before the first item then
insert new item at the head.
else
walk prev and curr pointers down the list until curr points AFTER where new item goes
insert new item between prev and curr

thanks :)
Topic archived. No new replies allowed.