【发布时间】:2022-01-09 13:26:31
【问题描述】:
我遇到了一个错误,在从while 循环接收用户输入后,我的代码不接受最后一个值。这个错误发生在一个特定的例子上,我不知道为什么会这样。
因此,例如,用户输入:
7
3 1 4 0 0 2 0
输出是:
3140020
但是,使用以下用户输入(这是具体示例):
7
3 0 1 0 0 2 0
输出应该是:
3010020
但是,输出是:
301002
我根本想不通。下面附上代码:
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(NULL), right(NULL) {}
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* construct_tree(){
int n;
cin >> n;
int curr_inp;
vector<TreeNode*> vec;
for (int i = 0; i < n; i++) {
cin >> curr_inp;
cout << curr_inp; // **this is the place of bug**
if (curr_inp != 0)
vec.push_back(new TreeNode(curr_inp));
else
vec.push_back(NULL);
}
for(int i = 0; i< floor(n/2);i++ )
{
vec[i]->left = vec[2*i+1];
vec[i]->right = vec[2*i+2];
}
cout << '\n';
return vec[0];
}
int main() {
TreeNode* root = construct_tree();
return 0;
}
【问题讨论】:
-
StackOveerflow 是一个问答网站,而不是调试服务。您是否尝试过自己在调试器中单步执行代码以查看其行为与您期望的不同之处? How to debug small programs
-
小问题:通过为
x提供默认值,您的 2 个TreeNode构造函数可以合并为 1 个。此外,您的代码存在内存泄漏,因为它不是delete'ing 任何new'edTreeNode对象。 -
@MarzukhAkib 只需将
cout << curr_inp;更改为cout << curr_inp<<endl;,您就会看到最后的输出。 -
@MarzukhAkib 不客气。
-
<math.h>-><cmath>。 “拥有裸指针”(即使用new创建的指针,如vec.push_back( new TreeNode( ... ) ))是不受欢迎的。实际上,您的程序正在泄漏该内存(可能会在程序完成后通过操作系统的内存保护清理来保存,但您的 program 正在泄漏)。考虑使用smart pointers,而不是自动释放他们的内存。并尝试取消using namespace std;。 ;-)
标签: c++ while-loop tree user-input tree-traversal