首页 > 解决方案 > 我的 python 查找函数返回 None 对象,尽管它准确地找到了密钥

问题描述

我正在编写代码以在二叉树中查找具有特定键的节点,尽管它可以正确找到节点但返回无

def Find(key,root):
    if(root):
        if (key>root.key):
            print("going right")
            Find(key,root.right)
        elif (key<root.key):
            print("going left")
            Find(key,root.left)
        elif (key == root.key):
            print("found" )
            print(root)
            return root
        else :
            print("not in the tree")
            return 0

temp = Find(5, bt.root) //Find the node with key 5 in the tree
print(type(temp))

// Output >> 
<__main__.Node object at 0x000000F8A7DCAAC8>
<class 'NoneType>

为什么它返回 None 类型,因为函数显然返回节点

标签: pythondata-structures

解决方案


更改Find(key,root.right)return Find(key,root.right)(与左侧类似)。

目前,当你找到元素时,你并没有返回它,所以函数隐式返回None


推荐阅读