Tree : Top View


Problem Statement :


Given a pointer to the root of a binary tree, print the top view of the binary tree.

The tree as seen from the top the nodes, is called the top view of the tree.

For example :

   1
    \
     2
      \
       5
      /  \
     3    6
      \
       4
Top View : 1 -> 2  -> 5 -> 6

Complete the function topView  and print the resulting values on a single line separated by space.

Input Format

You are given a function,

void topView(node * root) {

}
Constraints

 1 <= Nodes in the tree   <= 500

Output Format

Print the values on a single line separated by space.



Solution :



title-img


                            Solution in C :

In C++ :


/*
struct node
{
    int data;
    node* left;
    node* right;
};

*/

int w_min=-1,w_max=1,w=0;
void inorder(node *root,int w)
    { 
    if(root==NULL) return;
    if(w<w_min) w_min=w;
    if(w>w_max) w_max=w;
    if(root->left!=NULL) inorder(root->left,w-1);
    if(root->right!=NULL) inorder(root->right,w+1);
}
void top(node *root,int arr[],int w,int h,int arr2[])
    {
    if(root==NULL) return;
    if(arr[w-w_min]==0 || h<arr2[w-w_min])
        {
        arr2[w-w_min]=h;
       arr[w-w_min]=root->data;     
        }
    if(root->left!=NULL) top(root->left,arr,w-1,h+1,arr2);
    if(root->right!=NULL) top(root->right,arr,w+1,h+1,arr2);
}
void top_view(node * root)
{   
 inorder(root,0);
    int arr[w_max-w_min+1],arr1[w_max-w_min+1];
    for(int i=0;i<w_max-w_min+1;i++)
        {
        arr[i]=0;
        arr1[i]=90;
    }
  top(root,arr,0,1,arr1);
  for(int i=0;i<w_max-w_min+1;i++)
        {
      cout<<arr[i]<<" ";
    }  
}





In Java :



/*
   class Node 
       int data;
       Node left;
       Node right;
*/
void top_view(Node root)
{
    if(root==null)
        return;
    Stack st=new Stack();
     int size=0;
    int arr[]=new int[100];
   
    Node Left=null,Right=null;
    Left=root.left;
    Right=root.right;
     
        while(Right!=null)
        {
           
             arr[size]=Right.data;
                  
            size++;
            Right=Right.right;
            if(Right==null)
                {
                    for(int i=size-1;i>=0;i--)
                        {
                        st.push(arr[i]);
                       
                    }
                        
            }
           
    }
    
    st.push(root.data);
    while(Left!=null)
        {
             
        st.push(Left.data);
         
        Left=Left.left;
       
    }
    while(st.isEmpty()!=true)
        {
        System.out.print(st.pop()+" ");
    }
  
        
}




In pytho3 :



"""
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.info (the value of the node)
"""
from collections import defaultdict


def topView(root):
    # Write your code here
    if root is None:
        return None
    queue = [(root, 0)]
    hashtable = defaultdict(list)
    for node, level in queue:
        if node is not None:
            hashtable[level].append(node.info)
        if node.left is not None:
            queue.extend([(node.left, level - 1)])
        if node.right is not None:
            queue.extend([(node.right, level + 1)])
    if hashtable:
        for level in range(min(hashtable.keys()),
                           max(hashtable.keys()) + 1):
            print(hashtable[level][0], end=' ')
    else:
        return None


In C :


/*
struct node
{
    int data;
    node* left;
    node* right;
};

*/

struct node2
{
    struct node2* next;
    struct node2* prev;
    struct node* data;
    int idx;
};

typedef struct{
    int size;
    struct node2* front;
    struct node2* rear;
}queue;

struct node2* CreateNode(struct node * data, int idx)
{
    struct node2* n;
    // n = (struct node2*)malloc(sizeof(struct node2));
    // n->data = (struct node*)malloc(sizeof(struct node));
    // n->next = NULL;
    // n->prev = NULL;
    // n->idx = idx;
    struct node2* node2 = (struct node2*)malloc(sizeof(struct node2));

        node2->idx = idx;

        node2->prev = NULL;
        node2->next = NULL;
    node2->data = data;
    return node2;
}


queue CreateQueue()
{
    queue q;
    q.size = 0;
    q.front = NULL;
    q.rear = NULL;
    return q;
}

void
Enqueue(queue *q, struct node * data, int idx)
{
    struct node2* n = CreateNode(data, idx);
    if(q->front == NULL)
        q->front = q->rear = n;
    else
    {
        q->rear->next = n;
        q->rear = n;
    }
    q->size++;
}

struct node2*
Dequeue(queue *q)
{
    if(q->size <= 0)
        return NULL; 
    struct node2* del = q->front;
    q->front = q->front->next;
    q->size--;
    return del;
}

int
IsQueueEmpty(queue *q)
{
    return q == NULL || q->size == 0;
}

void topView(struct node * root) {
    int *a, i, arr_size, idx;
    arr_size = 1001;
    idx = 500;
    struct node2 *curr;
    a = (int*)calloc(arr_size, sizeof(int));
    for (i = 0; i < arr_size; i ++) {
        a[i] = -1;
    }
    queue que = CreateQueue();
    Enqueue(&que, root, idx);
    while (!IsQueueEmpty(&que)) {
        curr = Dequeue(&que);

        if (a[curr->idx] == -1) {
            a[curr->idx] = (int)curr->data->data;
        }
        if (curr->data->left != NULL) {
            Enqueue(&que, curr->data->left, curr->idx -1);
        }
        if (curr->data->right != NULL) {
            Enqueue(&que, curr->data->right, curr->idx +1);
        }
    }

    for (i = 0; i < 1001; i++) {
        if (a[i] != -1){
            printf("%d ", a[i]);
        }
    }
    // if (root == NULL) {
    //     return;
    // }
    // if (a[idx] == -1) {
    //     a[idx] = root->data;
    // }
    // traverse(root->left; a; idx - 1);
    // traverse(root->right; a; idx + 1);
    
  
}
                        








View More Similar Problems

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →