递归函数插入二叉搜索树无法按根访问节点
Binary Search Tree insertion by recursive function can't access node by root
我正在尝试使用C中的struct为二进制搜索树编写代码。我想制作两个单独的结构,分别称为"tree"answers"node"。然后我创建一个根的指针对象。我计划按顺序将所有节点链接到root的对象。但当我尝试从root的对象编译器转到节点时,会显示错误。我的代码是这样的:
#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中插入newnode,并返回一个插入了node的新树。
相关文章:
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 类成员函数无法访问同一类的私有结构节点?
- 在C++中删除双向链表的头节点后出现访问冲突异常
- 使用二进制搜索树中的迭代器对象访问左侧节点
- 尝试从单向链表C++中删除单个节点时出现读取访问冲突
- 有没有办法访问C++ Boost rtree 中的非叶节点
- C++:无法访问节点值
- 如何访问链式哈希表链表中的每个节点
- 从链表数组访问节点数据
- 使用访问者设计模式在N- ARY树中重复访问子节点值
- 如何在OMNet++中访问我的模拟的不同节点
- 在节点插件中访问 inspector_agent.h
- 链接列表节点的访问违规:C
- Dijkstra首个节点访问了
- 在图算法中,确定是否访问节点的最佳方法是什么?
- 如何在 <Target> MsBuild 中访问节点外部的项目元数据?
- 递归函数插入二叉搜索树无法按根访问节点
- Assimp访问节点名称时出错
- 访问节点矢量