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
| Term | Description |
|---|---|
| Root | Top node |
| Parent | Node with children |
| Child | Node below parent |
| Leaf | Node with no children |
| Height | Longest path to leaf |
| Depth | Distance 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
- Implement a tree node
- Traverse tree (preorder, inorder, postorder)
- Count leaf nodes
- 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.