在二进制搜索树中左右打印子树
Printing Left and Right Subtree in a Binary Search Tree
我的讲师对应打印二进制树的方式有特定的输出要求。他希望输出像这样:
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 );
}
}
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 在一定长度后从数组中打印时缺少整数
- 为什么这个 c++ 代码打印出长度 5,当我打印出字符串时,程序会自动终止?
- 在gem5中打印文件中的所有cache_blocks
- 打印数字图案
- Log4cpp:以UTC/GMT时区打印日期
- 如何使用gdb制作一个可以漂亮地打印每个对象的C++函数