【发布时间】:2019-01-11 22:48:37
【问题描述】:
打印二叉搜索树时出现堆栈溢出(线程 1: EXC_BAD_ACCESS (code=2, address=0x7ffeef3ffff8))。经过一番检查,在开始 inOrderTraversalRecursive 方法之前,树的根似乎变成了 nil。不知道为什么根变成零。我知道this 和this 资源,但到目前为止它们并没有帮助我。感谢您花时间回答我的问题。
在 main.m 文件中
#import <Foundation/Foundation.h>
@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
@property (nonatomic,strong) BSTNode *root;
- (void)insertNode:(int)value;
-(void)inOrderTraversal;
@end
@implementation BST
-(instancetype)init{
if (self = [super init]) {
self.root = [self initializeTreeNode];
}
return self;
}
- (BSTNode *)initializeTreeNode {
// By default, |data| is 0, |left| is nil, |right| is nil
return [[BSTNode alloc] init];
}
- (void)insertNode:(int)value {
self.root = [self insertNode:_root withData:value];
}
- (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)inOrderTraversal {
[self inOrderTraversalRecursive:self.root];
}
-(void)inOrderTraversalRecursive:(BSTNode *)root {
// inOrder = left - root - right
[self inOrderTraversalRecursive:root.left];
NSLog(@"%d",root.data);
[self inOrderTraversalRecursive:root.right];
}
@end
在 main.m 中
int main(int argc, const char * argv[]) {
@autoreleasepool {
BST *bst = [BST new];
[bst insertNode:50];
[bst insertNode:30];
[bst insertNode:20];
[bst insertNode:40];
[bst insertNode:70];
[bst insertNode:60];
[bst insertNode:80];
[bst inOrderTraversal];
}
return 0;
}
附言。
我基于 BST 的 geeksforgeeks java 实现设计了 BST 和 BSTNode 类。 Objective-C 中 BST(插入、查找、打印、删除)的正确实现是什么?好像哪里都找不到。
【问题讨论】:
标签: ios objective-c recursion data-structures binary-search-tree