I am getting stack-overflow(Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeef3ffff8)) while printing the binary search tree. After some inspection, it seems like the root of the tree becomes nil before starting the inOrderTraversalRecursive
method. Not sure why the root becomes nil. I am aware of this andthis resources, but they didn't help me so far. Thanks for taking the time to answer my question.
in main.m file
#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
inside 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;
}
PS.
I designed BST and BSTNode classes based on geeksforgeeks java implementation of BST. What is a proper implementation of BST(insert, find, print, delete) in Objective-C? Can't seem to find anywhere.