Έχω εφαρμόσει ένα BST σύνδεση με βάση το (δυαδικό δένδρο αναζήτησης) σε C ++ για ένα από αποστολή μου. Έχω γράψει ολόκληρη την τάξη μου και όλα λειτουργούν καλά, αλλά αποστολή μου με ρωτάει να σχεδιάσετε τις παραμονές φορές για:
a. A sorted list of 50000, 75000, and 100000 items
b. A random list of 50000, 75000, and 100000 items
Αυτό είναι εντάξει, μπορώ να εισάγετε τους αριθμούς, αλλά μου ζητά επίσης να καλέσετε το FindHeight()και CountLeaves()μεθόδους πάνω στο δέντρο. Το πρόβλημά μου είναι ότι έχω εφαρμόσει τις δύο λειτουργίες που χρησιμοποιούν recursion. Επειδή έχω μια τέτοια μεγάλη λίστα με τους αριθμούς παίρνω πάρει μια stackoverflowεξαίρεση.
Εδώ είναι ορισμός τάξη μου:
template <class TItem>
class BinarySearchTree
{
public:
struct BinarySearchTreeNode
{
public:
TItem Data;
BinarySearchTreeNode* LeftChild;
BinarySearchTreeNode* RightChild;
};
BinarySearchTreeNode* RootNode;
BinarySearchTree();
~BinarySearchTree();
void InsertItem(TItem);
void PrintTree();
void PrintTree(BinarySearchTreeNode*);
void DeleteTree();
void DeleteTree(BinarySearchTreeNode*&);
int CountLeaves();
int CountLeaves(BinarySearchTreeNode*);
int FindHeight();
int FindHeight(BinarySearchTreeNode*);
int SingleParents();
int SingleParents(BinarySearchTreeNode*);
TItem FindMin();
TItem FindMin(BinarySearchTreeNode*);
TItem FindMax();
TItem FindMax(BinarySearchTreeNode*);
};
FindHeight () Εφαρμογή
template <class TItem>
int BinarySearchTree<TItem>::FindHeight()
{
return FindHeight(RootNode);
}
template <class TItem>
int BinarySearchTree<TItem>::FindHeight(BinarySearchTreeNode* Node)
{
if(Node == NULL)
return 0;
return 1 + max(FindHeight(Node->LeftChild), FindHeight(Node->RightChild));
}
CountLeaves () εφαρμογή
template <class TItem>
int BinarySearchTree<TItem>::CountLeaves()
{
return CountLeaves(RootNode);
}
template <class TItem>
int BinarySearchTree<TItem>::CountLeaves(BinarySearchTreeNode* Node)
{
if(Node == NULL)
return 0;
else if(Node->LeftChild == NULL && Node->RightChild == NULL)
return 1;
else
return CountLeaves(Node->LeftChild) + CountLeaves(Node->RightChild);
}
Προσπάθησα να σκεφτώ πώς μπορώ να εφαρμόσει τις δύο μεθόδους χωρίς αναδρομή, αλλά είμαι εντελώς μείνει άναυδοι. Καθένας έχει οποιεσδήποτε ιδέες;













