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:
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.
In the above binary tree, the right view consists of nodes 4, 2, and the root 1.
The Right View of a binary tree can be calculated using recursion. Here's a step-by-step approach to understand the process:
Let's see a working example to help you visualize the process.
What is the Right View of the following binary tree?
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.
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! š