473,378 Members | 1,422 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

BST & recursion

Gentlemen,

I have a Binary Search Tree ADT that should use recursion for all operation
except for isEmpty() and isFull();

I have completed the insert function, and after inserting the numbers 10,
20, 30, 15, 5, 9, 3, 17, 4, 7, 6, 8, 11 and calling showStructure() I get
the following (works perfectly):

30
20<
17
15<
11
10<
9\
8
7<
6
5<
4
3/

After deleting 10 and calling showStructure() I get the following (lost the
right half of my tree):
30\
9\
8
7<
6
5<
4
3/

What am I doing wrong?
Thanks in advance,
Andrew
================================================== ==
Here is the code for my remove() function:

template < class DT, class KF >
bool BSTree<DT,KF>:: remove ( KF deleteKey )
{
return removeSub( root, deleteKey );
}

template < class DT, class KF >
bool BSTree<DT,KF>:: removeSub ( BSTreeNode<DT,KF>*& p, KF deleteKey )
{
if ( deleteKey < p->dataItem.key() )
{
removeSub ( p->left, deleteKey );
}
else if ( deleteKey > p->dataItem.key() )
{
removeSub ( p->right, deleteKey );
}
else
{
DT temp_data;
BSTreeNode<DT,KF>* temp_node = p;
if ( p->left == NULL )
{
p = p->right;
delete temp_node;
cout << "\nNode deleted";
return true;
}
else if ( p->right == NULL )
{
p = p->left;
delete temp_node;
return true;
}
else
{ int count=0;
while (p->right != NULL)
{
p->right->left = p->left;
// p->right->right = p->right; // causes infinite loop.
p = p->right;
}
delete temp_node;
}
}
return false;
}


Jul 19 '05 #1
12 4123
"David White" <no@email.provided> wrote...
Not ladies as well?
Sorry if this offends anyone.

I have completed the insert function, and after inserting the numbers 10, 20, 30, 15, 5, 9, 3, 17, 4, 7, 6, 8, 11 and calling showStructure() I get the following (works perfectly):

30
20<
17
15<
11
10<
9\
8
7<
6
5<
4
3/

After deleting 10 and calling showStructure() I get the following (lost

the
right half of my tree):
30\
9\
8
7<
6
5<
4
3/

I don't have time to analyse your code right now. But I see that you have
declared 'p' as a reference to a pointer, just as you did in your linked
list. I just thought I'd check that this is what you intended this time.
Yes this is intentional(actually, the choice is not mine). It is also one of
the reason why I have so much problem: I truly am missing something when it
comes to reference pointers and recursion.
An essential part of programming is debugging. What have you done to try to see where it's going wrong? An obvious starting point is to display a
message at each place you change the part of the tree that is attached to
another, and each time you delete a node. You call also try calling a
function to display the entire tree at certain points, so you can see the
total changes that have occurred so far. If you have the tools available,
single-stepping through the code would also help you find the problem.

DW


I have done this: the printout of the trees provided were done inside the
removeSub() function before and after removing the node containing 10.

I did not include that debugging information because I was advised that it's
not good practice to include such code within classes in an earlier post.
From debugging I see that the right portion of the tree falls off every time
I try to remove a node that has two children. Attempts to correct this
problem have left me with: 1) the reverse of the previous example (missing
left half of the tree). 2) infinite loops, 3) minimal amount of time to
find a solution, and 4) migraines.

Removal of leaves with one or no children woks fine, my real problem is with
nodes that have two children.

Thanks,
Andrew
Jul 19 '05 #2
[snip]

I did not include that debugging information because I was advised that it's not good practice to include such code within classes in an earlier post.
From debugging I see that the right portion of the tree falls off every time I try to remove a node that has two children. Attempts to correct this
problem have left me with: 1) the reverse of the previous example (missing
left half of the tree). 2) infinite loops, 3) minimal amount of time to
find a solution, and 4) migraines.

Removal of leaves with one or no children woks fine, my real problem is with nodes that have two children.

Thanks,
Andrew


This is how I was taught to remove an internal node from a binary tree.

If the node has two children, find the next node in sequence (i.e. go right
once, and then left as far as you can). This node must have at most one
child, so you can delete it using the techniques that have already worked
for you. But before you delete it, copy its value to the node you are trying
to delete.

HTH

john
Jul 19 '05 #3
Andrew Edwards <ed*******@spamfreeusa.com> wrote in message
news:TG**********************@twister.southeast.rr .com...
"David White" <no@email.provided> wrote...
An essential part of programming is debugging. What have you done to try to
see where it's going wrong? An obvious starting point is to display a
message at each place you change the part of the tree that is attached to another, and each time you delete a node. You call also try calling a
function to display the entire tree at certain points, so you can see the total changes that have occurred so far. If you have the tools available, single-stepping through the code would also help you find the problem.


I have done this: the printout of the trees provided were done inside the
removeSub() function before and after removing the node containing 10.

I did not include that debugging information because I was advised that

it's not good practice to include such code within classes in an earlier post.
Yes, for those trying to see what's wrong it's better without debugging
code.
From debugging I see that the right portion of the tree falls off every time I try to remove a node that has two children. Attempts to correct this
problem have left me with: 1) the reverse of the previous example (missing
left half of the tree). 2) infinite loops, 3) minimal amount of time to
find a solution, and 4) migraines.

Removal of leaves with one or no children woks fine, my real problem is with nodes that have two children.


In case you don't get an answer that solves the problem, I suggest that you
post the entire class, incuding the class definition, and your test code
that inserts the values. Though it's usually best to post the minimum code
that exhibits the problem, this kind of recursive tree code isn't trivial to
get one's head around without spending some time on it, so having a
complete, compilable test program might make it easier for someone to find
what's wrong.

Also, it isn't obvious at a glance what the loop in your final 'else' is
aiming to do. To delete one value, I can't see the necessity in any
circumstance to alter all the nodes below it, unless it is some sort of
optimization to make the tree more balanced. If it is re-balancing, try
replacing the node to be deleted with the appropriate one of its two
branches instead, just to see if you still have the same problem. At least
you might narrow it down.

DW

Jul 19 '05 #4
Andrew Edwards <ed*******@spamfreeusa.com> wrote in message
news:8v**********************@twister.southeast.rr .com...
Gentlemen,

I have a Binary Search Tree ADT that should use recursion for all operation except for isEmpty() and isFull();

I have completed the insert function, and after inserting the numbers 10,
20, 30, 15, 5, 9, 3, 17, 4, 7, 6, 8, 11 and calling showStructure() I get
the following (works perfectly):

30
20<
17
15<
11
10<
9\
8
7<
6
5<
4
3/

After deleting 10 and calling showStructure() I get the following (lost the right half of my tree):
30\
9\
8
7<
6
5<
4
3/

What am I doing wrong?
Thanks in advance,
Andrew
================================================== ==
Here is the code for my remove() function:

template < class DT, class KF >
bool BSTree<DT,KF>:: remove ( KF deleteKey )
{
return removeSub( root, deleteKey );
}

template < class DT, class KF >
bool BSTree<DT,KF>:: removeSub ( BSTreeNode<DT,KF>*& p, KF deleteKey )
{
I think I see a problem now. You are assuming that 'p' is not a null
pointer.
if ( deleteKey < p->dataItem.key() )
{
removeSub ( p->left, deleteKey );


But is it not possible that p->left is null here?

From the look of your tree, the node with value 20 has a null left node, and
10 is less than 20.

Or have I misunderstood your tree diagram?

DW

Jul 19 '05 #5
"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:3F**************@gascad.at...
You are not using paper and pencil to follow the operation of
your delete function:
template < class DT, class KF >
bool BSTree<DT,KF>:: removeSub ( BSTreeNode<DT,KF>*& p, KF deleteKey )


called with deleteKey == 10
p points to the root of the tree
deleteKey p
+---------+ +-------+
| 10 | | o |
+---------+ +---|---+
|
+---------+
|
|
| 30
| 20<
| 17
| 15<
v 11
10<
9\
8
7<
6
5<
4
3/

{
if ( deleteKey < p->dataItem.key() )


not true


Doesn't this test whether 10 is less than 30, and isn't it true that 10 is
less than 30?

DW

P.S. After having read your extraordinary response with increasing awe as
each line passed, I sincerely hope I am wrong!

Jul 19 '05 #6

"Andrew Edwards" <ed*******@spamfreeusa.com> wrote in message
news:8v**********************@twister.southeast.rr .com...
Gentlemen,

I have a Binary Search Tree ADT that should use recursion for all operation except for isEmpty() and isFull();


Just curious: what's an ADT??? I know what a binary search tree is, but a
"binary search tree ADT"?

-Howard
Jul 19 '05 #7
"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:3F***************@gascad.at...
Oh. I see where your problem is. You need to rotate the
tree 90 degrees clockwise. The tree is drawn this way

+-- right child
|
root =
|
+-- left child

It is easier to draw a tree this way. A simple recursive
function can do it. Drawing the tree in an upward position ...
+--- root ---+
| |
v v
left child right child

... is much more complicated.


Yes, I had got it the wrong way. I thought there was something odd about the
structure I saw.

DW

Jul 19 '05 #8
"Karl Heinz Buchegger" <kb******@gascad.at> wrote...

Please: In the future. If you post to 2 newsgroups, do so by
crossposting. Do *not* post the same message 2 times to 2
different newsgroups.
I apologize! I was simply overwhelmed when I decided to post that message
(after having worked on it for two days without coming any closer to
understanding what I was doing wrong). BTW, how does one post messages to
multiple newsgroups simultaneously? Just send it to all of them at the same
time? Will responses in one newsgroup automatically be submitted on all
others?

[snip]

I think you haven't understood what you need to do in the case
that a node has 2 subtrees and is to be deleted: You need to
*locate* the largest node in the right subtree and make that
one the new root. But locate does not mean that the intermediate
nodes are reconnected, yet this is what your code does.
You are 100% correct. I haven't a full grasp on correctly using reference
pointers and recursion as yet! Guess it's back to the drawing board for me.

When working with dynamic data structures, it is important
to use paper and pencil to draw an image of the data structure
and use that to verify each code line if it really is correct.
It is the only way to visually see, what your code does in reality!


Point well taken, I will be sure to incorporate this into my programming
practices.

Thanks allot,
I'll be sure to update you on my progress.
Andrew
Jul 19 '05 #9
"Howard" <al*****@hotmail.com> wrote...

Just curious: what's an ADT??? I know what a binary search tree is, but a
"binary search tree ADT"?

-Howard


Abstract Data Type:

http://www.nist.gov/dads/HTML/abstractDataType.html
Jul 19 '05 #10
Andrew Edwards <ed*******@spamfreeusa.com> wrote in message
news:vU**********************@twister.southeast.rr .com...
"Karl Heinz Buchegger" <kb******@gascad.at> wrote...

Please: In the future. If you post to 2 newsgroups, do so by
crossposting. Do *not* post the same message 2 times to 2
different newsgroups.


I apologize! I was simply overwhelmed when I decided to post that message
(after having worked on it for two days without coming any closer to
understanding what I was doing wrong). BTW, how does one post messages to
multiple newsgroups simultaneously?


It depends on your newsreader. Somewhere there should be an editable field
for the newsgroup. Try listing all newsgroups you want to post to there,
separated by commas.

DW

Jul 19 '05 #11
> What am I doing wrong?

You're not re-balancing the nodes. I've written an AVL-tree
implementation some time ago that does this balancing:
http://520032173347-0001.bei.t-online.de/avl.h
Jul 19 '05 #12


"Oliver S." wrote:
What am I doing wrong?


You're not re-balancing the nodes. I've written an AVL-tree
implementation some time ago that does this balancing:
http://520032173347-0001.bei.t-online.de/avl.h


:-)
Wait with rebalancing until the delete code works correctly
:-)

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 19 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Alex Vinokur | last post by:
========================================== Windows 2000 Professional CYGWIN_NT-5.0 1.5.4(0.94/3/2) GNU g++ version 3.2 20020927 (prerelease) GNU objdump 2.14.90 20030901...
5
by: herrcho | last post by:
int main() { printf("Input a line: "); wrt_it(); printf("\n\n"); return 0; } void wrt_it() {
8
by: Profetas | last post by:
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> void reverse(char *str); int main(void) { char *string; printf( "Enter a line of text:\n" );
2
by: jw | last post by:
what is the relation between a stack and recursion func. and if i have recursion funct(a return type void), void print(int n,int base){ static string digits="0123456789abcdef"; if(n>=base){...
28
by: Martin Jørgensen | last post by:
Hi, I have a "funny" question, which I think is pretty "healthy" to examine... This program is being investigated: - - - - - - - #include <iostream> using namespace std; #define DAYS 7
27
by: Chad | last post by:
The problem is: Write a recursive version of the function reverse(s), which reverses the string s in place. In "The C Answer Book", Second Edition, near the bottom of page 95, the authors say...
10
by: Immortalist | last post by:
Various aquisition devices that guide learning along particular pathways towards human biases. And as E.O. Wilson might say mental development appears to be genetically constrained. (1) Language...
19
by: pkirk25 | last post by:
I wonder if anyone has time to write a small example program based on this data or to critique my own effort? A file called Realm List.html contains the following data: Bladefist-Horde...
2
by: =?Utf-8?B?TWlrZQ==?= | last post by:
Hi. I have a website written entirely in classic ASP. My customer has asked if I can place one (1) aspx page into the website. They don't want the domain name to change between the aspx &...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.