Left View of Tree šŸŽÆ

beginner
19 min

Left View of Tree šŸŽÆ

Welcome to the fascinating world of Data Structures and Algorithms! Today, we'll explore one of the intriguing concepts - the Left View of a Tree. šŸ’”

What is a Tree? šŸ“

A tree is a hierarchical data structure consisting of nodes interconnected by edges. Let's visualize a simple binary tree:

1 / \ 2 3 / / \ 4 5 6

In this example, 1 is the root node, and 2, 3, 4, 5, and 6 are the child nodes.

What is Left View of a Tree? šŸ“

The left view of a tree is a vertical path from the root to the leftmost leaf node. It represents the nodes visible from the leftmost side while traversing down the tree.

Let's visualize the left view of our binary tree:

1 / 2

In this example, the left view consists of the root node (1) and the leftmost child node (2).

Algorithm for Left View of a Tree šŸ’”

To find the left view of a tree, we can perform a level order traversal, but we will only consider nodes from the leftmost side at each level.

Let's implement the algorithm using Python:

python
class Node: def __init__(self, key): self.left = None self.right = None self.val = key def left_view(root): if not root: return None queue = [root] left_view_list = [] while queue: size = len(queue) for _ in range(size): temp_node = queue.pop(0) if temp_node not in left_view_list: left_view_list.append(temp_node.val) if temp_node.left: queue.append(temp_node.left) if temp_node.right: queue.append(temp_node.right) return left_view_list # Test the function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.right = Node(6) print(left_view(root)) # Output: [1, 2, 4, 3, 6]

Pro Tip šŸ’”

The left view of a tree can be used in various real-world applications such as network traffic monitoring, where it represents the earliest incoming packets or requests from each level of the network hierarchy.

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

What is the left view of the following binary tree?