我试图在双递归函数调用后获得正常的增量索引。问题是我的索引不会随着每次调用而增加,并且我无法将我的数组与 BST 树进行比较来检查我的输入是否是前序。它仅适用于一次递归调用。这是我的代码:
int checkPreord(struct BST *root,int *v, int index)
{
if(!root)
{
return 1;
}
if(v[index]!=root->data){
printf("%d %d\n",v[index],root->data);
return 0;
}
checkPreord(root->left,v,index+1);
checkPreord(root->right,v,index+1);
}
最佳答案
我有一个解决方案,使用 vector 在每个函数调用时执行push_back,这是检查预购输入的完整程序。
#include <vector>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
struct BST{
struct BST *left;
struct BST *right;
int data;
};
void insert(struct BST **root,int val)
{
if(*root==NULL)
{
struct BST *tmp;
tmp=(struct BST*)malloc(sizeof(struct BST));
tmp->data = val;
tmp->left= tmp->right= NULL;
*root=tmp;
return;
}
if(val < (*root)->data)
insert(&(*root)->left,val);
else
insert(&(*root)->right,val);
return;
}
void checkPreord(struct BST *root, vector<int> &v2)
{
if(!root)
return;
v2.push_back(root->data);
checkPreord(root->left,v2);
checkPreord(root->right,v2);
}
void deleteTree(struct BST* node)
{
if (node == NULL) return;
deleteTree(node->left);
deleteTree(node->right);
free(node);
}
int main()
{
int ntests;
scanf("%d",&ntests);
while(ntests--)
{
struct BST *root=NULL;
int size;
scanf("%d",&size);
vector<int>v;
vector<int>v2;
for(int i=0;i<size;i++)
{
int val;
scanf("%d",&val);
v.push_back(val);
insert(&root,v[i]);
}
checkPreord(root,v2);
deleteTree(root);
if(v==v2)
printf("1\n");
else
printf("0\n");
}
return 0;
}
关于c - 双递归函数后使用顺序索引扫描数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59649237/