1

Hey guys so i have a problem and it is that my return statement is not executing. This is my sudo code. It searches a tree to see if an item is in the tree.

def search(self, i):
    if left child is None and right child is None
        if self.data == i:
            return True
        else:
            pass 
    elif self.data == i:
        return True
    else:
        if left child exists:
            return self.left.search(i)
        if right child exists:
            return self.right.search(i)

The code seems to work except when self.data == i, the code does not run the return True statement even though the if statement is executed. Does anyone know why this is? Thanks in advance!

EDIT: ADDED THE SELF PARAMETER. IT WAS SUPPOSED TO BE THERE, WAS A TYPO..

I inserted the numbers 3, 8, 2 and 1 into the tree and then searched for 1. I added a print statement if left child is None and right child is None: if self.data == i: print('self.data == i') return True I added that print statement when searching for 1 and the print statement did print which means that the if statement was executed, however, the return True statement does not execute

4

1 回答 1

1

我想您正在尝试进行二进制搜索,在这种情况下,您的代码中会出现一些问题。return 语句可能没有执行,因为条件self.data == i失败。另外,请注意,如果根有左孩子,则在您的原始代码中永远不会看到右孩子。

这是一个线性搜索的实现,我将把它作为练习修改为二分搜索。

def search(self, i):
    if self.data == i:
        return True

    if self.left is not None:
        if self.left.search(i):
            return True
    if self.right is not None:
        return self.right.search(i)
    return False
于 2013-04-05T04:04:20.500 回答