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

DSA — Trees

What is a Tree?

A hierarchical data structure with a root node and children.

class TreeNode:
    def __init__(self, data):
        self.data = data
        self.children = []

Tree Terminology

TermDescription
RootTop node
ParentNode with children
ChildNode below parent
LeafNode with no children
HeightLongest path to leaf
DepthDistance from root

Tree Traversal

# DFS - Preorder
def preorder(node):
    if node:
        print(node.data)
        for child in node.children:
            preorder(child)

# DFS - Inorder (for binary trees)
def inorder(node):
    if node:
        inorder(node.left)
        print(node.data)
        inorder(node.right)

# BFS - Level order
from collections import deque

def level_order(root):
    queue = deque([root])
    while queue:
        node = queue.popleft()
        print(node.data)
        for child in node.children:
            queue.append(child)

Binary Tree

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

Mini Practice

  1. Implement a tree node
  2. Traverse tree (preorder, inorder, postorder)
  3. Count leaf nodes
  4. Find tree height

Up Next

Continue with Binary Trees — binary tree operations.

Related Topics

Frequently Asked Questions about Trees

What is Trees in DSA?

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 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 Trees.

Why is Trees important in DSA?

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