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 :


                            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

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →

Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

View Solution →

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →

Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →

Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy

View Solution →