SwadhyAI Notes

All Python notes

Binary Trees in Python 🌳

Two Children Policy

A Binary Tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child.

💻 Implementation

python
class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key

# Creating root
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)

🔄 Traversals

  • Inorder: Left, Root, Right
  • Preorder: Root, Left, Right
  • Postorder: Left, Right, Root