C++ 在二叉搜索树中打印左、右子树
我的讲师对二叉树的打印方式有特定的输出要求。 他希望输出结果如下: 根{left_子树}-{right_子树} i、 e: 12{18}--{24} 18{6}--{14} 6{NULL}--{NULL} 等等 直到今天我才意识到这一点,我已经很兴奋我的程序开始工作了C++ 在二叉搜索树中打印左、右子树,c++,C++,我的讲师对二叉树的打印方式有特定的输出要求。 他希望输出结果如下: 根{left_子树}-{right_子树} i、 e: 12{18}--{24} 18{6}--{14} 6{NULL}--{NULL} 等等 直到今天我才意识到这一点,我已经很兴奋我的程序开始工作了 template<class elemType> struct nodeType { elemType info; nodeType<elemType> *lLink; nodeTy
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;
}
}
模板
结构节点类型
{
元素类型信息;
nodeType*lLink;
nodeType*rLink;
};
模板
void bSearchTreeType::printPreOrder(节点类型*root1)
{
if(root1!=NULL){
coutlink=newNode;
其他的
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 );
}
}
模板
void bSearchTreeType::printPreOrder(节点类型*根){
如果(根){
cout info您的printproorder
看起来不错。插入方法的实现是什么?您是否总是将lLink、rLink设置为NULL?当我插入时,lLink和rLink确实设置为NULL。当您出现SEGFULT和/或其他错误时,请向我们展示完整的示例。此外,请注意,您必须像示例6中那样打印NULL
s{NULL}--{NULL}
您的代码没有编译,我已经对大括号做了一些修改,可能是修复了。不管怎样,左边是lLink,右边是rLink…我想这个解决方案不会为空树打印{NULL},而是为每个非根节点打印两倍的信息。。。