我的导师对打印二叉树的方式有特定的输出要求。 他希望的输出是像这样:在二叉搜索树中打印左右子树
根{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;
}
}
我该如何让我的函数打印出左边的子树和右边的子树。每次我尝试一些事情时,我都会得到分段错误或输出奇怪的内存地址。
我在寻找指导和帮助,从伪代码到如何做到这一切都将是非常棒的。我只是困惑
编辑:要包括插入功能,我做什么时,我得到了错误
你'printPreOrder'看起来不错。什么是你的插入方法的实现?你是否总是将lLink,rLink设置为NULL? – PiotrNycz
当我插入 – Craig
时,lLink和rLink确实设置为NULL,告诉我们完整的示例,当您有段错误和/或其他错误时。 – PiotrNycz