Bottom View of Tree šŸŽÆ

beginner
19 min

Bottom View of Tree šŸŽÆ

Welcome to the exciting world of Data Structures and Algorithms! Today, we're going to dive into the Bottom View of a Tree 🌲, a concept that will help you understand and visualize trees in a unique way.

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

The Bottom View of a tree is an arrangement of the nodes of the tree such that all the nodes at a particular horizontal distance from the root are listed together. In simple terms, it's a representation that shows the nodes on the bottommost level of the tree from left to right.

Why Bottom View Matters? šŸ’”

Understanding the Bottom View of a tree is crucial as it helps in solving various problems related to trees. It provides a different perspective, making problem-solving more intuitive and efficient.

Understanding the Bottom View šŸŽÆ

Let's build our understanding with a simple example:

1 / \ 2 3 / / \ 4 5 6

In the above tree, the Bottom View would be: 4 5 6

Why? Because these are the nodes at the bottom level of the tree, listed from left to right.

Calculating the Bottom View šŸ’”

To calculate the Bottom View, we need to traverse the tree in a specific way. Here's a simple step-by-step process:

  1. Start from the root node.
  2. For each node, add its data to the Bottom View and subtract the data of all its children from the right side.
  3. Repeat this process for each child recursively.

Let's apply this to our example tree:

1 / \ 2 3 / / \ 4 5 6 For the root node (1): Add 1 to the Bottom View. For the left child (2): Add 2 to the Bottom View and subtract 4 from the right side. For the right child (3): Add 3 to the Bottom View and subtract 5 from the right side. For the left child of the left child (4): There are no nodes to its right, so no subtraction is needed. For the left child of the right child (5): There are no nodes to its right, so no subtraction is needed. For the right child of the right child (6): There are no nodes to its right, so no subtraction is needed. So, the updated tree would look like: 1 / \ 2 3 / / \ 4 5 6 With the Bottom View being: 4 5 6

Code Implementation šŸ’”

Here's a simple Python implementation of the Bottom View calculation:

python
def bottomView(root): # Create an empty dictionary to store the bottom view bottomView = {} # A queue to hold the nodes with their distances from the root queue = [] # A tuple to store the node and its distance queue.append((root, 0)) while queue: node, distance = queue.pop(0) # Update the bottom view for the current node bottomView[distance] = node.data if distance not in bottomView else bottomView[distance] + node.data # Enqueue the children of the current node with their distances for child in node.children: queue.append((child, distance + 1)) # Print the bottom view for key in sorted(bottomView.keys()): print(bottomView[key], end=" ")

Quiz šŸ“

Quick Quiz
Question 1 of 1

What is the Bottom View of the following tree?