我有一个二叉树的部分实现,它不能正常工作。我相信我在Objective-C中缺少有关结构内存管理的基本知识,但不确定它是什么(除了malloc)。当我尝试基于结构创建新的树节点时,我得到了
线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x0)
这使我相信我没有为此结构指针创建内存位置。在Objective-C中执行此操作的正确方法是什么? (下面的代码)
感谢您抽出宝贵的时间来答复。从逻辑角度来看,该代码似乎是正确的,因此不能确定问题出在哪里。
编辑 我已经基于@trungduc的响应修改了源代码。但是现在我在printDescription方法中出现堆栈溢出 问题:
Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeef3fffe8) // on line [self printDescription:root.left];
PS。 我确实看到了this question,但没有帮助。我也看到了this repo,但是我不确定对某些实施细节感到满意,因此我最终没有关注它。有谁知道如何在Objective-C中做树和图的任何好的指南/教程?
Main.m
#import <Foundation/Foundation.h>
// BSTNode is an Objective-C class
@interface BSTNode : NSObject
@property (nonatomic, assign) int data;
@property (nonatomic, strong) BSTNode *left;
@property (nonatomic, strong) BSTNode *right;
@end
@implementation BSTNode
@end
@interface BST: NSObject
- (BSTNode *)insertNode:(BSTNode *)root withData:(int)data;
- (void)printDescription:(BSTNode *)root;
@end
@implementation BST
- (BSTNode *)initializeTreeNode {
// By default, |data| is 0, |left| is nil, |right| is nil
return [[BSTNode alloc] init];
}
- (BSTNode *)insertNode:(BSTNode *)root withData:(int)data {
if(!root) {
root = [self initializeTreeNode];
root.data = data;
} else if (root.data >= data) {
root.left = [self insertNode:root.left withData:data];
} else {
root.right = [self insertNode:root.right withData:data];
}
return root;
}
- (void)printDescription:(BSTNode *)root {
// in order left - root - right
[self printDescription:root.left];
NSLog(@"%d",root.data);
[self printDescription:root.right];
}
@end
以及main方法内:
int main(int argc, const char * argv[]) {
@autoreleasepool {
BST *bst = [[BST alloc] init];;
BSTNode *root = [[BSTNode alloc]init];
[bst insertNode:root withData:20];
[bst insertNode:root withData:15];
[bst insertNode:root withData:25];
[bst printDescription:root];
}
return 0;
}
答案 0 :(得分:1)
您崩溃是因为您在node->data
是node
时致电NULL
。
在这种情况下,我建议将BSTNode
定义为Objective-C类。您可以在下面尝试我的代码。
// BSTNode is an Objective-C class
@interface BSTNode : NSObject
@property (nonatomic, assign) int data;
@property (nonatomic, strong) BSTNode *left;
@property (nonatomic, strong) BSTNode *right;
@end
@implementation BSTNode
@end
@interface BST: NSObject
- (BSTNode *)insertNode:(BSTNode *)root withData:(int)data;
- (void)printDescription:(BSTNode *)root;
@end
@implementation BST
- (BSTNode *)initializeTreeNode {
// By default, |data| is 0, |left| is nil, |right| is nil
return [[BSTNode alloc] init];
}
- (BSTNode *)insertNode:(BSTNode *)root withData:(int)data {
if(!root) {
root = [self initializeTreeNode];
root.data = data;
} else if (root.data >= data) {
root.left = [self insertNode:root.left withData:data];
} else {
root.right = [self insertNode:root.right withData:data];
}
return root;
}
- (void)printDescription:(BSTNode *)root {
if (!root) {
return;
}
// in order left - root - right
[self printDescription:root.left];
NSLog(@"%d",root.data);
[self printDescription:root.right];
}
@end