c - 双递归函数后使用顺序索引扫描数组

标签 c recursion binary-search-tree

我试图在双递归函数调用后获得正常的增量索引。问题是我的索引不会随着每次调用而增加,并且我无法将我的数组与 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/

相关文章:

C++ - 递归结构 - 这可能吗?

java - 使用递归而不是循环打印嵌套数组中的元素

javascript - 尝试查找 BST 的范围和时出现错误的递归

c - 在 C 中获取操作系统的默认颜色

C、用文本文件保存/读取NULL

c - 指针指向的元素的索引

c - 查找 sscanf() 的长度而不存储结果

algorithm - 二叉树最大路径和中的递归调用解释

java - 将二叉搜索树转换为双向链表 - 不起作用

java - 叶到根 BST 遍历