Python3二叉树值存在性判断代码报错,求同结构修正方案
The error 'BinaryTree' object has no attribute 'data' happens because your LOOKUP method in the BinaryTree class is trying to access self.data, but the BinaryTree instance doesn't have a data attribute—only the Node instances do. The BinaryTree has a root attribute which is a Node, so we need to start our lookup from that root node and traverse recursively through its children.
Here's the corrected code that retains your existing structure while fixing the issues:
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class BinaryTree: def __init__(self, rootdata): self.root = Node(rootdata) def LOOKUP(self, lookupval): # Helper function to recursively check each node def traverse(node): if not node: return False if lookupval == node.data: return True elif lookupval < node.data: return traverse(node.left) else: return traverse(node.right) # Start traversal from the root node return traverse(self.root) # Create the tree and add nodes Tree = BinaryTree(24) Tree.root.left = Node(11) Tree.root.left.left = Node(199) Tree.root.left.right = Node(167) Tree.root.right = Node(2) Tree.root.right.right = Node(8) # Test the lookup print(Tree.LOOKUP(11)) # Output: True print(Tree.LOOKUP(13)) # Output: False
Key Fixes Explained:
- Removed
self.datareference: Instead of trying to access data directly on theBinaryTree, we use a helper functiontraversethat takes aNodeas input. - Recursive traversal: The helper function checks if the current node is
None(returnsFalse), matches the value (returnsTrue), or recurses on the left/right child based on whether the lookup value is smaller/larger than the current node's data. - Proper result propagation: Unlike your original code which returned
Falseimmediately after checking a child, we return the result of the recursive call, allowing the lookup to continue down the tree.
Note: Your tree structure isn't a valid Binary Search Tree (BST) because values like 199 are placed as left children of smaller nodes (11). This means the lookup won't find values that are placed incorrectly (e.g., Tree.LOOKUP(199) would return False even though the node exists). If you want a proper BST, you should add nodes in a way that maintains the BST property, but that's a separate issue from fixing the lookup method.
内容的提问来源于stack exchange,提问作者Steven H

