Kumar-laxmi / Algorithms

A Repository for algorithms in C, C++, Python and Java
Apache License 2.0
325 stars 367 forks source link

Top View of Binary Tree #1691

Closed Devchawla2608 closed 1 year ago

Devchawla2608 commented 1 year ago

Is your feature request related to a problem? Please describe. Top view of a binary tree is the set of nodes visible when the tree is viewed from the top

Describe the solution you'd like 1.) Create an empty map to store the top view nodes with their corresponding column values. 2.) Create a queue of pairs, where each pair consists of a Node and an integer representing the column value. 3.) Enqueue a pair containing the root node and column 0 into the queue. 4.) While the queue is not empty 5.) Dequeue the front element of the queue and store the Node in top and the column value in col. 6.) If the column value col does not exist in map, insert a new key-value pair in map with the column value as the key and the data of top as the value. 8.) If top->left is not NULL, enqueue a pair containing top->left and col-1. 9.) If top->right is not NULL, enqueue a pair containing top->right and col+1. 10.) Create an empty vector called ans to store the top view nodes in the correct order. 11.) Iterate over each pair in map and append the value (node data) to the ans vector. 12.) Return the ans vector.

image

Devchawla2608 commented 1 year ago

@Kumar-laxmi please assign this to me under SSOC'23. I'm ready to contribute in all 4 languages

Kumar-laxmi commented 1 year ago

This algo has been implemented