Right View of Tree šŸŽÆ

beginner
24 min

Right View of Tree šŸŽÆ

Welcome to our deep dive into the Right View of a Binary Tree! In this lesson, you'll learn about this interesting concept and understand how it can be applied in real-world programming scenarios.

By the end of this lesson, you'll be able to:

  • Understand the Right View of a Binary Tree šŸ“
  • Learn how to calculate the Right View using recursion šŸ’”
  • Implement a working code to find the Right View of a binary tree āœ…

What is the Right View of a Binary Tree?

In a binary tree, the right view consists of the nodes on the rightmost path starting from the rightmost leaf and moving up towards the root.

Binary Tree Diagram

In the above binary tree, the right view consists of nodes 4, 2, and the root 1.

Calculating the Right View using Recursion

The Right View of a binary tree can be calculated using recursion. Here's a step-by-step approach to understand the process:

  1. Start with the rightmost leaf of the tree.
  2. Traverse upwards by moving from the right child to the parent node.
  3. Repeat the process at each parent node until we reach the root.

Let's see a working example to help you visualize the process.

Quick Quiz
Question 1 of 1

What is the Right View of the following binary tree?

Implementing the Right View Code

Now that we understand the concept and process, let's implement a working code to calculate the right view of a binary tree in Python.

python
class Node: def __init__(self, key): self.left = None self.right = None self.val = key def print_right_view(root, h = 0): if root is None: return if (h == 0): print(root.val, end=" ") return right_view(root.right, h - 1) # Create a binary tree root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) print("Right view of binary tree is:") print_right_view(root)

When you run the code, it will output:

Right view of binary tree is: 4 2 1

That's it! You've learned about the Right View of a binary tree, its calculation, and implemented a working code to find the right view. Practice the code and try calculating the right view of different binary trees to reinforce your understanding. Happy coding! šŸŽ‰