Welcome to our deep dive into the fascinating world of Vertical Traversal! In this comprehensive guide, we'll explore the concepts, real-world applications, and practical examples of vertical traversal. Let's get started!
Vertical Traversal, also known as Top-down or Depth-first Search (DFS), is a traversal technique used for exploring or searching tree or graph data structures. It starts from the root node and explores as far as possible along each branch before backtracking.
Let's dive into a simple example to understand Vertical Traversal better. We'll use a binary tree to illustrate the concept.
1
/ \
2 3
/
4
Here's a simple Python implementation of the Vertical Traversal algorithm for the given binary tree:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def verticalTraversal(root):
# Define the height of the tree
height = getHeight(root)
# Create a hash map to store the result
vtMap = {}
for i in range(height, -1, -1):
# Create an empty list for this level
levelMap[i] = []
# A utility function to get maximum height of tree
def getHeight(node):
if node is None:
return 0
else:
return max(getHeight(node.left), getHeight(node.right)) + 1
# A utility function to get the minimum vertical distance
# from a given node to root
def minVerticalDistance(node, level):
if root is None:
return 0
return (level - node.val)
# A utility function to insert a new node with given key in BST
def insert(node, key):
if node is None:
return Node(key)
if key < node.val:
node.left = insert(node.left, key)
else:
node.right = insert(node.right, key)
return node
# Insert the given binary tree in a sorted manner in vtMap
def verticalOrder(root):
if root is None:
return
# First insert the root in the appropriate level
levelMap[root.val] = levelMap.get(root.val, []) + [root.val]
# Recursively insert the left and right child nodes
verticalOrder(root.left)
verticalOrder(root.right)
# Sort the list of elements for each level
for i in levelMap:
levelMap[i].sort()
# Now print the vertical traversal
for i in sorted(levelMap.keys()):
print(levelMap[i])
# Create a binary tree
root = insert(None, 1)
root = insert(root, 2)
root = insert(root, 4)
root.left = insert(root.left, 3)
# Function call to perform vertical traversal
verticalTraversal(root)u ā v, vertex u comes before v in the ordering.In this lesson, we've delved into the world of Vertical Traversal, understanding its importance, and implementing it in a binary tree. We've also explored some real-world applications of this technique. Now, it's time for you to practice and solidify your understanding.
Which traversal technique does Vertical Traversal belong to?
Keep exploring, keep learning! Happy coding! ššš