noobsmcgoobs - 1 year ago 110

Objective-C Question

I want to write a search function for a Binary Search Tree. How can I write it so that I can return from the base case

`if(root.data == node.data){return node;}`

`-(Node*)search:(Node*)node{`

if(root == nil){

return node;

}

if(root.data == node.data){

return node;

}

if (node.data < root.data){

root = root.left;

[self search:root];

}

if (node.data > root.data) {

root = root.right;

[self search:root];

}

}

Answer Source

You get the error because you don't return anything from your `search:`

method under certain conditions. You must return something. You also don't make any use of the return value when you recursively call `search:`

.

You probably want something more like this:

```
- (Node *)search:(Node *)node {
if (root == nil) {
return node;
}
if (root.data == node.data) {
return node;
} else if (node.data < root.data) {
root = root.left;
return [self search:root];
} else // node.data > root.data
root = root.right;
return [self search:root];
}
}
```