-
ordered binary tree
Hi developers,
I only wanne know: Is this solution right?
Problem:
I have to write a function wich returns
the largest key (node->key == Max) in an ordered binary tree.
int Maxkey(const node*)
I must do it on brute force (so easiest ) way.
Given:
Code:
Struct node {
Int key;
Struct node *left, *right;
}
I have developted the code. Can someone look at it if it's right(good).
My sollution:
Code:
int Maxkey( const node *n) {
int max=o;
if (n == NULL)
return;
else while (n->right != NULL) {
if (max > n->key)
max = n->key;
n->right;
}
return max;
}
Is this code ok??
Thanx people
Holland
-
Why don't you just write a test case to see if it gives you the right answer? If you're even getting this to compile, and actually calling the function, then you have a tree. Does it give you the answer you expect? Even when you switch the order of the information in the nodes? If so, then it's probably working right. If not, fix it.
Quzah.
-
well I wrote my test case. For me it's right.
I ask a second opinion???
Thanx
-
>I ask a second opinion???
It's overkill. You can simply rely on the structure of a binary search tree to give you the correct value:
Code:
int MaxKey ( const node *root )
{
assert ( root != NULL );
while ( root->right != NULL )
root = root->right;
return root->key;
}
>Struct node {
C is case sensitive, the keyword is struct, not Struct.
>Int key;
Ditto, int, not Int.
>int Maxkey( const node *n) {
Unless you've tyepdef'd the node structure, you need to specify the keyword struct when declaring an instance.
>int max=o;
What's o? Did you mean 0?
>return;
Return what? If you say you're going to return a value, you'd better return a value.
>if (max > n->key)
This test is redundant, and incorrect. If max is greater than n->key, and you're looking for the largest value in the tree, why do you set max to n->key?
>n->right;
This doesn't do anything. Try assigning this to n and you'll have better results.