[英]Insert element into a BST in C
I've got a structure type like the following: 我有一个如下的结构类型:
typedef struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
To add an element to my 给我添加一个元素
TreeNode* insert(TreeNode *root, int val){
TreeNode* a;
a = root;
int i;
if(a==NULL){
a -> val = val;
a -> left = NULL;
a -> right = NULL;
}
else if(a->val < val){
return insert(root->left,val);
}
else if(a->val > val)
return insert(root->right,val);
}
This gives no output when i evaluate it. 当我评估它时,没有输出。 What is my fault? 我怎么了
a == NULL
case, you need to allocate memory for the node. 在a == NULL
情况下,您需要为节点分配内存。 Otherwise a -> val
is illegal. 否则a -> val
是非法的。 root = insert(root, val)
然后,当您调用该函数时,将其命名为root = insert(root, val)
The code is below. 代码如下。
TreeNode* insert(TreeNode *root, int val){
TreeNode* a;
a = root;
int i;
if(a==NULL){
// Allocate memory here
a = malloc(sizeof (root));
if (a== NULL)
{
// Malloc error, You can exit the program or print a debug message here
}
a -> val = val;
a -> left = NULL;
a -> right = NULL;
}
else if(a->val < val){
return insert(root->left,val);
}
else if(a->val > val)
return insert(root->right,val);
return a;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.