我的讲师对二进制树的打印方式有特定的输出要求。 他希望输出如此:
root {left_subtree} - {right_subtree}
即:
12 {18} - {24}
18 {6} - {14}
6 {NULL} - {NULL}
等...
直到今天我才意识到这一点,我很高兴能让我的计划工作。
template<class elemType>
struct nodeType
{
elemType info;
nodeType<elemType> *lLink;
nodeType<elemType> *rLink;
};
template<class elemType>
void bSearchTreeType<elemType>::printPreOrder(nodeType<elemType> *root1)
{
if(root1 != NULL) {
cout<<root1->info<<" "<<"{"<<root1->lLink<<"}"<<endl;//this is where I get the errors
printPreOrder(root1->lLink);
printPreOrder(root1->rlink);
}
}
template <class elemType>void bSearchTreeType<elemType>::insert(const elemType& insertItem){
nodeType<elemType> *current; //pointer to traverse the tree
nodeType<elemType> *trailCurrent; //pointer behind current
nodeType<elemType> *newNode; //pointer to create the node
newNode = new nodeType<elemType>; newNode->info = insertItem;
newNode->lLink = NULL;
newNode->rLink = NULL;
if (root1 == NULL)
root1 = newNode;
else {
current = root1;
while (current != NULL)
{
trailCurrent = current;
if (current->info == insertItem)
{
cout << "The item to be inserted is already ";
cout << "in the tree -- duplicates are not allowed." << endl;
return;
}
else if (current->info > insertItem)
current = current->lLink;
else
current = current->rLink;
}//end while
if (trailCurrent->info >insertItem)
trailCurrent->lLink = newNode;
else
trailCurrent->rLink = newNode;
}
}
如何让我的函数打印出左子树和右子树。每当我尝试某些东西时,我都会输出分段错误或输出奇怪的内存地址。
我正在寻找指导和帮助,从伪代码到如何做的任何事都会很棒。我很困惑
已编辑:要包含插入功能以及我在收到错误时所执行的操作
答案 0 :(得分:1)
你可以尝试这些方法:
template<class elemType>
void bSearchTreeType<elemType>::printPreOrder(nodeType<elemType> *root) {
if( root ) {
cout << root->info << " " << endl;
cout << "{";
if( root->left ) {
cout << root->left->info;
}
else {
cout << "NULL";
}
cout << "} -- ";
cout << "{";
if( root->right ) {
cout << root->right->info;
}
else {
cout << "NULL";
}
cout << "}";
cout << endl;
printPreOrder( root->left );
printPreOrder( root->right );
}
}