Q:

Building a tree in Python with "parent" support

The problem: the child of the root has itself as a child. I'm new to building data structures in Python, so I'm writing code as if I were writing C++. Here's my code:
class node:
    key = None
    value = None
    parent = None
    children = []

    def __init__(self,key,val):
        self.key = key
        self.val = val

if __name__ == "__main__":
    root = node(50,50)
    child = node(20,20)
    child.parent = root
    root.children.append(child)
    print(root)
    print(child)
    print(root.children)
    print(child.parent)
    print("Why does child have itself as a child??!!")
    print(child.children)

I cannot seem to figure out what the problem is.

A:

You are using class attributes where you should be using instance attributes.
class Node:
    def __init__(self, key, val):
        self.key = key
        self.val = val
        self.children = []
        self.parent = None

root = node(50, 50)
child = node(20, 20)
child.parent = root
root.children.append(child)

You can modify __init__ to simplify building a tree.
class Node:
    def __init__(self, key, val, parent=None):
        self.key = key
        self.val = val
        self.parent = parent
        if parent is not None:
            parent.children.append(self)

root = node(50, 50)  # sets root.parent = None
child = node(20, 20, root)  # sets child.parent = root and adds child to root.children

