user3353890 user3353890 - 5 months ago 13
Objective-C Question

How do I find the minimum value of a binary tree?

I'm trying to find the minimum value of a binary tree. Every time I run my code I get a long 5 digit number like '32675'. I'm pretty sure my understanding of pointers is wrong, but I'm not positive. If I could get some advice I'd really appreciate it. Thanks!

Node definition

@interface Node:NSObject {
@property (nonatomic, strong) Node *left;
@property (nonatomic, strong) Node *right;
@property (nonatomic, assign) int *value;

-(id)initWithValue:(int)val {
self = [super init];
if(self) {
self.value = &(val);
self.left = nil;
self.right = nil;
return self;

Insert Algorithms for Tree

-(void)insertValue:(int)value {
Node *node = [[Node alloc] initWithValue:value];
[self insertNode:node];

-(void)insertNode:(Node *)node {
if (root == nil) {
root = node;
} else {
[node insertNode:node];

Insert Algorithms for Node

-(void)insertNode:(Node *)node{
if (node.value < self.value) {
[self insertOnLeft:node];
} else {
[self insertOnRight:node];

-(void)insertOnLeft:(Node *)node {
if (self.left == nil) {
self.left = node;
} else {
[self.left insertNode:node];

-(void)insertOnRight:(Node *)node {
if (self.right == nil) {
self.right = node;
} else {
[self.right insertNode:node];

3 values go in to my tree:

[tree insertValue:4];
[tree insertValue:6];
[tree insertValue:2];

int min = [tree findMinimum];

Tree's findMinimum method is called

-(int)findMinimum {
assert(root != nil);
return [root findMinimum];

Which call's root's findMinimum - root is a node

-(int)findMinimum {
Node *node = self;
int min = 0;
while (node != nil) {
min = *(node.value);
node = node.left;
return min;


Your are filling your tree not with integers but with stack addresses which are immediately invalid with this code:

self.value = &(val);

Here val is a parameter variable, which will disappear as soon as the method returns. Taking its address should only be done in rare circumstances and that address should never be stored in a location which outlives val.

Change the type of the value property of Node to int and remove the uses of address of (&) and indirection (*) associated with that property.