Question

I'm a beginner to c++ and am having problems with finding the minimal element of a BST. The BST is implemented in this way:

class Tree{
struct Node {
int Element;
Node *Left, *Right;
Node(int Element) : Element(Element), Left(0), Right(0){}
};

Node *Root;
void InOrder(void(*Action)(int&), Node *Current);
void Destroy(Node *Current);

public:

Tree() : Root(0){}
void Insert(int Element);
void InOrder(void(*Action)(int&)) {InOrder(Action,Root);}
void Destroy() {Destroy(Root);}
};

The InOrder, Destroy and Insert methods are implemented like this:

void Tree::Insert(int Element) {
Node *NewElement = new Node(Element);
if(!Root) Root = NewElement;

 else {
 Node *Previous, *Current = Root;

  while(Current) {
   Previous = Current;
   if(Element < Current->Element) Current = Current->Left;
   else Current = Current->Right;
  }

 if(Element < Previous->Element) Previous->Left = NewElement;
 else Previous->Right = NewElement;
 }
}

void Tree::InOrder(void(*Action)(int&),Node *Current) {
  if(Current) {
  InOrder(Action,Current->Left);
  Action(Current->Element);
  InOrder(Action,Current->Right);
}

}

void Tree::Destroy(Node *Current) {
 if(Current) {
  Destroy(Current->Left);
  Destroy(Current->Right);
  delete Current;
 }
}

And the main function and function which I use to print the numbers look like this:

void Print(int &e) {
 cout << e << endl;
}

int main() {
 Tree t;
 while(1) {
 int Number;
 cout << "Insert number (insert 0 to end): ";
 cin >> Number;
 if(Number == 0) break;
 t.Insert(Number);
 }

 t.InOrder(Print);
 t.Destroy();
 getch();
}

As you may noticed, the InOrder method is implemented also, maybe it can be used in some way to help solve my problem... Sorry for my bad English :/

Was it helpful?

Solution

The minimal value would be the first value that calls Action in the above code. Go left as far as you can, and the minimal value you shall find...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top