简体   繁体   中英

Difficulty with storing key-value pairs in Binary Search Tree in Python

I need to store user objects with each key in my BST. class BSTNode represents the nodes of our tree.

Here is the code of my BST node class:

class BSTNode(): 
    def __init__(self, key, value=None): 
        self.key = key 
        self.value = value
        self.left = None
        self.right = None
        self.parent = None

When I try inputting usernames as keys and user objects as values

tree = BSTNode(john.username, john)

The following error gets thrown:

NameError                                 Traceback (most recent call last)
Input In [62], in <cell line: 2>()
      1 #Level 0
----> 2 tree = BSTNode(john.username, john)

NameError: name 'john' is not defined

What am I doing wrong?

Is john object already created, seems python is not able to identify john.username . Also better to store the key as the object itself rather than john.username as it will resolve to the username value itself.

It says john is not created. it means error is at last line at which you are making instance of BSTNode and passing value of john.username and john is not defined previously. so please defined the variable john first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM