在objective-c中使用struct创建二叉树

在objective-c中使用struct创建二叉树,objective-c,tree,binary-tree,Objective C,Tree,Binary Tree,我想用objective-c中的struct创建一个二叉树,下面是我正在做的事情: struct mytree{ int value; struct mytree *parent; struct mytree *left; struct mytree *right; }; - (void)insertmytree: (struct mytree *)root value:(int)value{ struct mytree *temp; if

我想用objective-c中的struct创建一个二叉树,下面是我正在做的事情:

struct mytree{
    int value;
    struct mytree *parent;
    struct mytree *left;
    struct mytree *right;
};

- (void)insertmytree: (struct mytree *)root value:(int)value{
    struct mytree *temp;
      if (root == nil) {
         temp->value = value;
         temp->left = nil;
         temp->right = nil;
         root = temp;
      return;
      }

      if (value < root->value) {
         return [self insertmytree:root->left value:value];
      }else{
         return [self insertmytree:root->right value:value];
      }
}

它不起作用,请给我指一个正确的方向

我还没有测试过,但应该可以

struct mytree{
    int value;
    struct mytree *parent;
    struct mytree *left;
    struct mytree *right;
};

- (void)insertmytree: (struct mytree *)root value:(int)value{
    struct mytree *temp = malloc(sizeof(struct mytree));
      if (root == nil) {
         temp->value = value;
         temp->left = nil;
         temp->right = nil;
         root = temp;
      return;
      }

      if (value < root->value) {
         return [self insertmytree:root->left value:value];
      }else{
         return [self insertmytree:root->right value:value];
      }
}
struct mytree{
int值;
结构mytree*父级;
结构mytree*左;
struct mytree*右;
};
-(void)insertmytree:(struct mytree*)根值:(int)值{
struct mytree*temp=malloc(sizeof(struct mytree));
如果(根==nil){
温度->值=值;
温度->左=零;
温度->右=零;
根=温度;
返回;
}
如果(值<根->值){
返回[自插入MyTree:root->左值:value];
}否则{
返回[自插入MyTree:root->右值:value];
}
}
然后,当您从树中删除项时,您需要一些mekanism来清理动态分配的内存。

在(Objective-)C(++)中,您必须显式分配在堆上动态创建的任何对象/结构,仅声明指向对象/结构的指针类型的变量不会分配对象/结构并将其引用存储在变量中

例如:

NSMutableArray *myArray;
struct mytree *temp;
创建一个变量,
myArray
,类型为指向可变数组的指针,
NSMutableArray*
。它不创建数组。声明:

myArray = [NSMutableArray new];
temp = (struct mytree *)malloc( sizeof(struct mytree) );
分配一个新的可变数组,并在
myArray
中存储对它的引用

对于堆分配的C结构,您需要使用
malloc()
,它将对象/结构的大小作为参数,您可以通过
sizeof
获得该参数

请举例说明:

NSMutableArray *myArray;
struct mytree *temp;
创建变量
temp
,该变量可以保存对
结构mytree
的引用,以及以下语句:

myArray = [NSMutableArray new];
temp = (struct mytree *)malloc( sizeof(struct mytree) );
在堆上创建一个(未初始化的)
struct mytree
,并将对它的引用存储在
temp

当不再需要动态分配的内存时,还需要释放它。例如:

free(temp);
将释放
temp
引用的对象/结构,该对象/结构必须是使用
malloc
创建的对象/结构(或
malloc
系列中的另一个函数)。注意:此语句不会更改
temp
中的值,因此在此调用之后,
temp
中的值是对解除分配内存的引用,如果
temp
停留在附近,您可能希望为其分配
NULL
,以避免意外访问解除分配内存


HTH

“它不起作用”是不够的信息。告诉我们它是如何失败的。你有编译错误吗?你的程序崩溃了吗?至少有一件事是这个代码不起作用的,那就是永远不会分配temp,所以第一个if语句中的所有内容都是nil。