簡體   English   中英

python:遞歸函數不返回true或false

[英]python: recursive function not returning true or false

我已經在python中實現了我的不平衡二叉樹,現在想為其尋找一種可以返回True和False的搜索方法。 但是,我現在已經創建了此遞歸函數,該函數在打印結果方面有效,但僅返回“ None”。

我猜這是因為僅是最后一個遞歸調用返回了某些內容,而外部的則沒有。

我該如何解決? 我覺得這應該是微不足道的,我困擾我,我是如此迷失。

def traverseSearch(self, ID, current):

    if current == None: # if we have not found our goal, the current node is null
        print("not found")
        return False

    if current.ID == ID: # succes statement
        print("found")
        return True
    if ID > current.ID: # call recursive on left children if data is bigger
        self.traverseSearch(ID, current.rightChild)

    if ID < current.ID: # call recursive on Right children if data is bigger
        self.traverseSearch(ID, current.leftChild)

現在將其更改為以下內容,但似乎仍返回nonetype

def traverseSearch(self, ID, current):

    if current == None: # if we have not found our goal, the current node is null
        print("not found")
        return False

    if current.ID == ID: # succes statement
        print("found")
        return True
    if ID > current.ID: # call recursive on left children if data is bigger
        self.traverseSearch(ID, current.rightChild)

    if ID < current.ID: # call recursive on Right children if data is bigger
        self.traverseSearch(ID, current.leftChild)

您的猜測是正確的; 您只需要返回遞歸調用的結果。

        return self.traverseSearch(ID, current.Child)

不用擔心 我們都會迷失在某些事后看來很明顯的事情上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM