create a binary tree in python

To create a binary tree in Python, we can define a class Node to represent the nodes in the tree. Each node should have a left child node and a right child node, which can be other instances of Node or None if they don't exist. Here's a basic implementation:

main.py
class Node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data
118 chars
6 lines

To build the tree, we can create a root node and then add child nodes as needed. For example, to create the following binary tree:

main.py
        1
       / \
      2   3
     / \
    4   5
52 chars
6 lines

We can use the following code:

main.py
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
107 chars
6 lines

To traverse the tree, we can use various tree traversal algorithms such as inorder, preorder and postorder. Here's an example implementation of the inorder traversal algorithm:

main.py
def inorder_traversal(node):
    if node:
        inorder_traversal(node.left)
        print(node.data)
        inorder_traversal(node.right)
142 chars
6 lines

We can call this function with the root node to print out the values of the nodes in sorted order:

main.py
inorder_traversal(root)
# Output: 4 2 5 1 3
44 chars
3 lines

I hope this helps!

gistlibby LogSnag