noobsmcgoobs noobsmcgoobs - 6 months ago 41
Objective-C Question

Return Statement in Objective C for Binary Search Tree Search Function

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;}
without getting compiler warnings about the method returning nothing. In this case, root is an ivar that's part of the BST class that these methods are a part of.

-(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

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];
    }
}