输出正确,但每次打印输出后程序崩溃
Output is correct but program crashes after printing the output everytime
我在不使用递归的情况下实现了预定的二叉树遍历。这是我的代码:
#include<iostream>
#include<stack>
using namespace std;
struct node{
int data;
node *left;
node *right;
};
node *getNewNode(int data){ //method for creating new node
node *newNode = new node();
newNode->data=data;
newNode->left=newNode->right = NULL;
return newNode;
}
node *Insert(node *root , int data){ //Method for insert new data in tree
if(root == NULL){
root = getNewNode(data);
}
else if(data>root->data){
root->right = Insert(root->right,data);
}
else{
root->left = Insert(root->left,data);
}
return root;
}
void Print(node *root){ //Method for preorder traversal with recursion
if(root == NULL){
return;
}
cout<<root->data<<" ";
Print(root->left);
Print(root->right);
}
void preOdr(node *root){ //Without recursion
stack<node*> stk;
cout<<root->data<<" ";
do{
a:
if(!(root->right==NULL&&root->left==NULL)){
if(root->right!=NULL){
stk.push(root->right);
}
if(root->left!=NULL){
stk.push(root->left);
}
}
cout<<stk.top()->data<<" ";
root=stk.top();
stk.pop();
goto a;
}
while(!stk.empty());
}
int main(){
node *root = NULL;
root = Insert(root,10);
root = Insert(root,6);
root = Insert(root,15);
root = Insert(root,3);
root = Insert(root,9);
root = Insert(root,11);
root = Insert(root,17);
root = Insert(root,11);
root = Insert(root,62);
root = Insert(root,135);
root = Insert(root,30);
root = Insert(root,98);
root = Insert(root,117);
root = Insert(root,176);
Print(root);
cout<<endl;
preOdr(root);
return 0;
}
在我的程序中,我还创建了使用递归的预序遍历方法,以验证非递归方法给出的输出,该方法Print()
。
在非递归方法中,首先我打印根,然后分别将该节点的左右子节点(如果有)推送到堆栈。在此之后,我从堆栈中弹出项目并重复上述过程,直到堆栈不为空。
当我运行此代码时,它正确提供输出,但之后崩溃。我不明白名为preOrd()
的方法有什么问题。为了更好地理解,我附加了完整的代码。
您的preOrd()
函数被搞砸了。
1.不要使用转到
首先,你在循环的末尾有一个goto
,在循环的开头跳跃。 这样可以防止验证while
条件,并导致永远循环。 一旦堆栈为空,它将尝试pop
/top
导致UB(这里是崩溃)!
每次你想使用goto
时,请三思而后行! 更喜欢break
中断循环,或continue
正确循环。 这将避免将来出现此类问题。
今日名言:"goto - 臭名昭著的goto。
2.然后修改循环的逻辑
如果你只是注释掉goto
,它会更好地工作,但在第二级之后停止(这次没有崩溃)。显然,您不会将所需的所有内容都推送到堆栈上。
以下是修订版:
void preOdr(node *root){ //Without recursion
stack<node*> stk;
stk.push(root); // put the root not on th stack and
// then process it like the others
while (!stk.empty()) {
root=stk.top();
stk.pop();
cout<<root->data<<" "; // get and show top of stack
if(root->right) // then push the childern
stk.push(root->right);
if(root->left)
stk.push(root->left);
}
}
现场演示
你有一个 goto 关键字,它将你带回到该代码块的开头,这是末尾 while 的目的。这是循环中的循环,没有检查。
相关文章:
- 数组类 阵列的打印输出
- 我要求用户输入大小和数组,但是当我打印矢量时,它仅显示'0'作为输出
- 程序打印 % 后预期输出
- 为什么Qt Creator的应用程序输出不能从spdlog记录器打印
- 为什么打印 c 样式字符串的'address of index n'会导致子字符串的输出
- 为什么打印"OK"会改变输出?
- 打印输出在主,而不是在函数中
- 该程序没有产生输出,而是卡在一个循环中,几秒钟后消失并打印被杀死?
- 存储和打印字符,但输出不是预期的
- 执行ls命令并打印输出
- 为什么如果我从键盘输入EOF克里昂不要在运行窗口打印程序的输出?
- 将C++输出打印到文本文件
- 如何仅使输出打印一次
- 以未格式化的输出 c++ 打印输出
- 如何将谷歌测试输出打印到文本文件
- 为类打印输出(打印调试信息)的最佳实践是什么?
- 将命令行输出打印到Linux(Ubuntu)的文本文件中
- 输出打印地址而不是3D数组指针中的值
- 将Qt C++输出打印到QML中写入的应用程序屏幕
- 多线程文本输出打印到dos控制台重叠/混乱输出