You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

二叉搜索树递归search函数移入nodeList类后调用失败及功能改造需求

解决二叉搜索树搜索函数移入类后的调用问题与打印逻辑整合

问题原因

把独立的search函数移入nodeList类后出现异常,核心是没适配类方法的特性:

  • 类的实例方法必须以self作为第一个参数,用来指代当前节点实例
  • 递归时需要通过子节点实例调用search方法,而非直接传入节点参数

修正后的完整代码

class nodeList:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

    def search(self, value):
        # 找到目标节点,打印成功信息并返回节点
        if self.value == value:
            print(f"Node found with value: {self.value}")
            return self
        
        # 当前节点值大于目标,递归左子树
        if self.value > value:
            if self.left:
                return self.left.search(value)
            # 左子树为空,确认未找到
            print("Search was unsuccessful")
            return None
        
        # 当前节点值小于目标,递归右子树
        if self.right:
            return self.right.search(value)
        # 右子树为空,确认未找到
        print("Search was unsuccessful")
        return None

# 创建示例二叉搜索树
root = nodeList(10) 
root.left = nodeList(7) 
root.right = nodeList(15) 
root.left.left = nodeList(4) 
root.left.right = nodeList(9) 

# 调用类中的search方法
root.search(15)  # 输出: Node found with value: 15
root.search(20)  # 输出: Search was unsuccessful

关键修改说明

  • 将search改为类的实例方法,用self指代当前节点
  • 递归时通过self.left.search(value)或self.right.search(value)触发子节点的搜索
  • 把成功/失败的打印逻辑直接整合到方法内部,无需在外部额外判断结果

内容的提问来源于stack exchange,提问作者Syed Hassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 17:40:09