</>
Skip to content
DSA lessons (19/55)

DSA — Binary Trees

What is a Binary Tree?

A tree where each node has at most two children.

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

Traversals

# Preorder: Root → Left → Right
def preorder(root):
    if root:
        print(root.data)
        preorder(root.left)
        preorder(root.right)

# Inorder: Left → Root → Right
def inorder(root):
    if root:
        inorder(root.left)
        print(root.data)
        inorder(root.right)

# Postorder: Left → Right → Root
def postorder(root):
    if root:
        postorder(root.left)
        postorder(root.right)
        print(root.data)

Height and Size

def height(root):
    if not root:
        return -1
    return 1 + max(height(root.left), height(root.right))

def size(root):
    if not root:
        return 0
    return 1 + size(root.left) + size(root.right)

Count Leaves

def count_leaves(root):
    if not root:
        return 0
    if not root.left and not root.right:
        return 1
    return count_leaves(root.left) + count_leaves(root.right)

Mini Practice

  1. Implement a binary tree
  2. Perform all traversals
  3. Calculate height and size
  4. Count leaf nodes

Up Next

Continue with Binary Search Trees — BST operations.

Related Topics

Frequently Asked Questions about Binary Trees

What is Binary Trees in DSA?

Binary Trees is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Binary Trees?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Binary Trees.

Why is Binary Trees important in DSA?

Binary Trees is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.