#include<iostream> using namespace std; typedef struct node { int num; int flag; struct node *leftchild; struct node *rightchild; }Node; int n, M; int a[210]; int temp=0; void creat(Node* &root,int r,int num) { if (temp == n) { root = NULL; } else { root = new Node; root->flag = r; root->num = num; creat(root->leftchild, 0, a[temp]); creat(root->rightchild, 1, a[temp]); } temp++; } void show(Node* root) { if (root != NULL) { show(root->leftchild); cout << root->num<<" "; show(root->rightchild); } } int main() { cin >> n >> M; for (int i = 0; i < n; i++) { cin >> a[i]; } Node* root=new Node; creat(root, -1, -1); cout << temp; show(root); return 0; }帮我找出代码的问题
时间: 2024-03-11 09:47:55 浏览: 12
这段代码有几个问题:
1. 在结构体定义中,需要用分号“;”结束。
2. 在 creat 函数中,应该先判断 temp 是否等于 n,再进行相应的操作。
3. 在 creat 函数中,应该先判断 root 是否为空,再进行相应的操作。
4. 在 creat 函数中,应该将参数 r 改为 flag,因为 flag 是结构体中的变量名。
5. 在 creat 函数中,应该将参数 num 改为 a[temp],因为 num 是结构体中的变量名,而 a[temp] 才是要传入的值。
6. 在 main 函数中,应该先把 root 初始化为 NULL。
7. 在 show 函数中,应该先判断 root 是否为空,再进行相应的操作。
下面是修改后的代码:
```
#include<iostream>
using namespace std;
typedef struct node {
int num;
int flag;
struct node *leftchild;
struct node *rightchild;
}Node;
int n, M;
int a[210];
int temp=0;
void creat(Node* &root,int flag,int num) {
if (temp == n) {
root = NULL;
return;
}
if(root==NULL) {
root = new Node;
root->flag = flag;
root->num = num;
creat(root->leftchild, 0, a[temp]);
creat(root->rightchild, 1, a[temp]);
}
temp++;
}
void show(Node* root) {
if (root != NULL) {
show(root->leftchild);
cout << root->num<<" ";
show(root->rightchild);
}
}
int main() {
cin >> n >> M;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
Node* root=NULL;
creat(root, -1, -1);
cout << temp;
show(root);
return 0;
}
```