Question:
Calculating the elements available in the Top View of Binary Tree

Summary:

Here we have to print the top view of a binary tree. 


What is the Top view of a binary tree?

Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. 


Solution:

#User function Template for python3


# Tree Node

# class Node:

#     def __init__(self, val):

#         self.right = None

#         self.data = val

#         self.left = None


class Solution:

    

    #Function to return a list of nodes visible from the top view 

    #from left to right in Binary Tree.

    def topView(self,root):

        

        # code here

        if not root : return []

        dic = dict()

        

        q=[]

        q.append((0, root))

        while q :

            hd , root = q.pop(0)

            if hd not in dic : 

                dic[hd]= root.data

                

            

            if root.left : q.append((hd-1 , root.left))

            if root.right : q.append((hd+1 , root.right))

            

            

         

        res=[]   

        sorted_dic = sorted(dic.items(), key = lambda x: x[0])

        

        for i,j in sorted_dic:

            res.append(j)

        

        return res


Explanation:

This Python code defines a class Solution with a method topView to return a list of nodes visible from the top view of a binary tree, from left to right. Here's a summary:


  1. The topView method takes the root node of a binary tree as input.

  2. It initializes an empty dictionary dic to store the nodes visible from the top view, where the keys represent the horizontal distance (hd) from the root, and the values represent the node data.

  3. It initializes a queue q and enqueues a tuple containing the horizontal distance (initialized as 0) and the root node.

  4. While the queue is not empty, it dequeues a tuple representing the horizontal distance and the current node. If the horizontal distance is not present in the dictionary, it adds the current node data to the dictionary with the horizontal distance as the key.

  5. It then enqueues the left and right child nodes along with their respective horizontal distances adjusted by -1 and +1, respectively.

  6. After traversing the entire tree, it sorts the dictionary by keys (horizontal distance) using the sorted function and appends the corresponding node data to the result list res.

  7. Finally, it returns the list res, containing the nodes visible from the top view of the binary tree from left to right.


Overall, this code efficiently computes the top view of a binary tree using a breadth-first traversal approach.


Suggested blogs:

>How to route between different components in React.js?

>How to save python yaml and load a nested class?-Python

>How to send multiple HTML form fields to PHP arrays via Ajax?

>What is data binding in Angular?

>What is microservice architecture, and why is it better than monolithic architecture?

>What is pipe in Angular?

>What makes Python 'flow' with HTML nicely as compared to PHP?

>What to do when MQTT terminates an infinite loop while subscribing to a topic in Python?

>Creating custom required rule - Laravel validation


Ritu Singh

Ritu Singh

Submit
0 Answers