-
Why does this crash??
code:
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
#include <dos.h>
class tnode
{
public:
int nodevalue;
tnode *left, *right;
//Constructor
tnode (int item, tnode *lptr = NULL,tnode *rptr = NULL)
{
nodevalue=item;
left=lptr;
right=rptr;
}
};
tnode *maxnode=NULL;
void findmaxvalue(tnode* tempnode)
{
if (tempnode!=NULL)
{
if (tempnode->nodevalue > maxnode->nodevalue)
{
maxnode=tempnode;
}
findmaxvalue(tempnode->left);
findmaxvalue(tempnode->right);
}
}
int main()
{
system("CLS");
//Building the tree
tnode *b,*c,*d,*e,*f,*root;
d= new tnode(5);
e= new tnode(38);
f= new tnode(42);
b= new tnode(15, d);
c= new tnode(40,e,f);
root=new tnode(35,b,c);
findmaxvalue(root);
cout<<"\n The maximum value in the tree is :: "<< maxnode->nodevalue;
getch();
return 0;
}
/code
-
You have to initialize maxvalue before you access it. It's still NULL when you first access it in findmaxvalue.
-
-
Code:
void findmaxvalue(tnode* tempnode)
{
if (tempnode!=NULL)
{
if (tempnode->nodevalue > maxnode->nodevalue)
The first time you call findmaxvalue, maxnode is NULL. So when it attemts to find maxnode->nodevalue, it will throw an error. Try having 'tnode maxnode = root;' instead of =NULL.
-
Changing
tnode *maxnode=NULL;
to
tnode *maxnode=root;
errors: root' : undeclared identifier
and
'initializing' : cannot convert from 'int' to 'class tnode *'
what did I miss ??
-
I got it now! Thanks a ton!!
-
Actually there is quite many errors in your code but dont worry, we will help you :D.
The problem lies in your finmaxvalue
Code:
void findmaxvalue(tnode* tempnode)
{
if (tempnode!=NULL)
{
if (tempnode->nodevalue > maxnode->nodevalue)
{
maxnode=tempnode;
}
findmaxvalue(tempnode->left);
findmaxvalue(tempnode->right);
}
}
To find the maximum value in a B-Tree is easy (both with recursion or iteration, IŽll use recusrion here). What you really want to find is the element which is the most rightfar in the tree.
In other words
Code:
void findmaxvalue(tnode* tempnode)
{
/* You have a root node which is NULL */
if (tempnode == NULL)
return ;
/* Reached 'last rightmost' (your case 42) element */
if (tempnode->right == NULL)
{
maxnode = tempnode;
return ;
}
/* Pass next right childen to findmaxvalue recursivly */
findmaxvalue(tempnode->right);
}
IŽll leave findminvalue as an exercise for you to figure out (almost identical with findmaxvalue).
Why not implement a B-Tree with class and high-level functions for it???
Also read this and this before posting next time.