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

Python二叉树节点搜索报错排查:AttributeError问题咨询

Fixing Your Binary Tree Search Errors

Hey there, let's break down what's going wrong with your binary tree search code and fix it step by step:

Key Issues Identified

  • Mismatched Method Name: The root cause of your AttributeError is that you defined your search method as is_exist, but you're calling exists() in the recursive steps. Python can't find a method named exists on your Node class, hence the error.
  • Duplicate Method Definition: You've written the is_exist method twice. The second definition overwrites the first, which is redundant and can lead to unexpected behavior. Remove one of them.
  • Inconsistent Return Values: Your current code returns (None, None) when the value isn't found, but returns self.data when it is. This mixed return type makes your test assertions unreliable (since a non-empty tuple like (None, None) evaluates to True in a boolean check).
  • Typo in printTree: The method calls self.left.PrintTree() (capital P), but the method is defined as printTree (lowercase p). This will throw an error if you ever try to use the printTree method.

Fixed Complete Code

class Node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

    def printTree(self):
        # Fixed typo: PrintTree -> printTree
        if self.left:
            self.left.printTree()
        print(self.data, end=" ")
        if self.right:
            self.right.printTree()

    def insert(self, data):
        """ Compare the new value with the parent node """
        if self.data:
            if data < self.data:
                if self.left is None:
                    self.left = Node(data)
                else:
                    self.left.insert(data)
            elif data > self.data:
                if self.right is None:
                    self.right = Node(data)
                else:
                    self.right.insert(data)
        else:
            self.data = data

    def is_exist(self, val):
        # Fixed method call: exists -> is_exist
        if val < self.data:
            if self.left is None:
                return False  # Consistent return type: False when not found
            return self.left.is_exist(val)
        elif val > self.data:
            if self.right is None:
                return False
            return self.right.is_exist(val)
        else:
            return True  # Return True when found, or self.data if you need the value

def test_binary_tree():
    root = Node(10)
    assert root.is_exist(10) == True
    root.insert(4)
    assert root.is_exist(4) == True
    root.insert(11)
    assert root.is_exist(11) == True
    root.insert(3)
    assert root.is_exist(3) == True
    root.insert(770)
    assert root.is_exist(770) == True
    root.insert(523)
    assert root.is_exist(523) == True
    root.insert(43)
    assert root.is_exist(43) == True
    # Test a non-existent value to ensure it works
    assert root.is_exist(999) == False
    print("All tests passed!")

test_binary_tree()

Additional Notes

  • If you prefer to return the node's data when found instead of a boolean, you can adjust the is_exist method to return self.data when matched, and None when not found. Just make sure your assertions match this behavior (e.g., assert root.is_exist(4) == 4).
  • The printTree method was updated to use end=" " so the output is cleaner, but that's optional based on your formatting preference.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 09:42:42