繁体   English   中英

递归函数插入二叉搜索树无法通过根访问节点

[英]Binary Search Tree insertion by recursive function can't access node by root

我正在尝试使用 C 中的结构编写二叉搜索树的代码。我想制作两个单独的结构,称为“树”和“节点”。 然后我创建了一个 root 的指针对象。 我计划将所有节点依次链接到根对象。 但是当我尝试从 root 的对象编译器转到 node 时显示错误。 我的代码是这样的:

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node{
    int data;
    struct node* left;
    struct node* right;
}*new_node ;
struct tree{
    int count;
    struct node* p;
}*root ;
void create_root(){
    root = (tree *) malloc(sizeof(tree));
    root->count=0;
    root->p=NULL;
}
void insert_node(tree *root){
    if(root->p == NULL and root->count==0){
        root->p = new_node;
        root->count++;
        return;
    }
    else if(root->p->left==NULL and root->p->right==NULL){
        if(root->p->data > new_node->data){
            root->p->left =  new_node;
        }
        else if(root->p->data <= new_node->data){
            root->p->right =  new_node;
        }
        root->count++;
        return;
    }
    else{
        if(root->p->data <= new_node->data){
            return insert_node(root->p->right);
        }
        if(root->p->data > new_node->data){
            return insert_node(root->p->left);
        }
    }
}
int main()
{
    create_root();
    new_node = (node *) malloc(sizeof(node));
    new_node->data=321;
    new_node->left=NULL;
    new_node->right=NULL;
    insert_node(*root);
    return 0;
}

编译器显示如下错误:

/home/ahashans/Documents/bst_new.cpp||In function ‘void 
insert_node(tree*)’:|
/home/ahashans/Documents/bst_new.cpp|37|error: cannot convert ‘node*’ to 
‘tree*’ for argument ‘1’ to ‘void insert_node(tree*)’|
/home/ahashans/Documents/bst_new.cpp|37|error: return-statement with a 
value, in function returning 'void' [-fpermissive]|
/home/ahashans/Documents/bst_new.cpp|40|error: cannot convert ‘node*’ to 
‘tree*’ for argument ‘1’ to ‘void insert_node(tree*)’|
 /home/ahashans/Documents/bst_new.cpp|40|error: return-statement with a 
 value, in function returning 'void' [-fpermissive]|
 /home/ahashans/Documents/bst_new.cpp||In function ‘int main()’:|
 /home/ahashans/Documents/bst_new.cpp|51|error: cannot convert ‘tree’ to 
 ‘tree*’ for argument ‘1’ to ‘void insert_node(tree*)’|
  ||=== Build failed: 5 error(s), 0 warning(s) (0 minute(s), 0 second(s)) 
  ===|

理想情况下,您的 insert_node 的签名应该为

tree* insert_node(node *new_node, tree* mytree)

这意味着请在 mytree 中插入 new_node 并返回一个带有插入节点的新树。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM