Pastebin

Paste #2244: None

< previous paste - next paste>

Pasted by hdn@turbogris

Download View as text

class TreeNode:
    def __init__(self, data, parent=None, left = None, right = None):
        self.data   = data
        self.left   = left
        self.right  = right
        self.parent = parent

    def __repr__(self):
        return '%s[%s](%s, %s)' % (self, self.parent, repr(self.left), repr(self.right))

    def __str__(self):
        return self.data


# Make some tree nodes
a = TreeNode('A')
b = TreeNode('B')
c = TreeNode('C')
d = TreeNode('D')
e = TreeNode('E')
f = TreeNode('F')
g = TreeNode('G')

# Build tree structure
a.left  = b
a.right = c
b.parent = a
c.parent = a

b.left  = d
d.parent = b


c.left  = e
c.right = f
e.parent = c
f.parent = c

e.right = g
g.parent = e


def walk(node, level=0):
    print ' ' * level + node.data
    if node.left:
        walk(node.left, level+1)
    if node.right:
        walk(node.right, level+1)


walk (a)

#              A
#             / \
#            B   C
#           /   / \
#          D   E   F
#               \
#                G



New Paste


Do not write anything in this field if you're a human.

Go to most recent paste.