简体   繁体   English

将元素插入C中的BST

[英]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? 我怎么了

  1. In the a == NULL case, you need to allocate memory for the node. a == NULL情况下,您需要为节点分配内存。 Otherwise a -> val is illegal. 否则a -> val是非法的。
  2. Also need to add a return to the code. 还需要添加返回代码。 You can return (a). 您可以返回(a)。 Then when you call the function, you call it as 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.

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