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
AttributeErroris that you defined your search method asis_exist, but you're callingexists()in the recursive steps. Python can't find a method namedexistson yourNodeclass, hence the error. - Duplicate Method Definition: You've written the
is_existmethod 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 returnsself.datawhen it is. This mixed return type makes your test assertions unreliable (since a non-empty tuple like(None, None)evaluates toTruein a boolean check). - Typo in
printTree: The method callsself.left.PrintTree()(capital P), but the method is defined asprintTree(lowercase p). This will throw an error if you ever try to use theprintTreemethod.
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_existmethod to returnself.datawhen matched, andNonewhen not found. Just make sure your assertions match this behavior (e.g.,assert root.is_exist(4) == 4). - The
printTreemethod was updated to useend=" "so the output is cleaner, but that's optional based on your formatting preference.
内容的提问来源于stack exchange,提问作者Benn
相关产品推荐
相关产品推荐

