在二进制搜索树中左右打印子树

Printing Left and Right Subtree in a Binary Search Tree

本文关键字:打印 左右 二进制 搜索树      更新时间:2023-10-16

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

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

我将如何获得我的功能以打印出左子树和右子树。每当我尝试某些东西时,我会得到分段故障或怪异的内存地址。

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

编辑:要包括插入功能以及当我获取错误时所做的工作

您可以沿着这些行尝试:

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