0

我的讲师对二叉树的打印方式有特定的输出要求。他希望输出是这样的:

根 { left_subtree }-{ right_subtree }

IE:

12 {18} --{24}

18 {6} --{14}

6 {NULL} --{NULL}

ETC...

直到今天我才意识到这一点,我已经很兴奋我的程序可以运行了。

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;    
    }
}

如何让我的函数打印出左子树和右子树。每次我尝试某些东西时,都会出现分段错误或输出奇怪的内存地址。

我正在寻找指导和帮助,从伪代码到如何做的任何事情都会很棒。我只是困惑

已编辑:包括插入功能以及出现错误时的操作

4

1 回答 1

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 );
   }
}
于 2012-11-11T19:59:18.840 回答