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

Python3二叉树值存在性判断代码报错,求同结构修正方案

Fixing the Binary Tree Lookup Error

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:

  1. Removed self.data reference: Instead of trying to access data directly on the BinaryTree, we use a helper function traverse that takes a Node as input.
  2. Recursive traversal: The helper function checks if the current node is None (returns False), matches the value (returns True), or recurses on the left/right child based on whether the lookup value is smaller/larger than the current node's data.
  3. Proper result propagation: Unlike your original code which returned False immediately 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 15:27:42