Skip to main content

Top View of Binary Tree in Java Vijay Sinha The Crazy Programmer

Given a binary tree we have to print top view. We will discuss our approach to solve this problem along with its implementation and code in Java language. We will also analyze the time and space complexity of our implementation.

The top view of binary tree means the set of nodes visible when the tree is viewed from top. In other words, a node is included in our top view if it is the topmost node at it’s respective horizontal distance.

We calculate the horizontal distance as follows:

  • The Horizontal Distance of Root of tree=0.
  •  Horizontal Distance of Left Child=Horizontal Distance of it’s Parent Node – 1.
  • The Horizontal Distance of Right Child=Horizontal Distance of it’s Parent Node + 1.

Let us consider binary tree give below:

Top View of Binary Tree in Java

The top view of this tree will give output:  2  1  3  6.

Explanation:

The nodes are highlighted in the figure above. We put nodes with same horizontal distance together. We start from the root node 1 at level 1 the horizontal distance is 0 at root, then we go down each level and print the topmost node for that horizontal distance. At level 2 node 2 is the topmost node with horizontal distance -1 so print it, at the same level 2 node 3 is the topmost node with horizontal distance 1. At level 3 node 6 is the topmost node with horizontal distance 2.

Input:     // Tree is Viewed from top here             hd=Horizontal distance
   
  hd=0             20                                   -- level 1
                /       \
               /         \
  hd=-1       10          30         hd= +1             -- level 2
            /   \        /   \
           /     \      /     \
  hd=-2   5      15    25      35    hd= +2             -- level 3 
                hd=0   hd=0

Output: 5  10  20  30  35

Approach (Using Level Order Traversal and Hashing)

The idea of our approach is to put nodes with same horizontal distance together. Then, print the topmost node with the respective horizontal distance. We get the topmost node by maintaining a map and doing level order traversal. At a particular level if the node with the given horizontal distance is not present in our map, we add the node’s hd as a key to our map and it’s data as the value. We maintain a pair class of node and hd to maintain each node’s hd and level in our Queue while processing them. We add a given hd only once which ensures only the topmost node is present in our map. Lastly, we print the values of the map. In order to print the top view from left to right we use a Tree Map to order the Map with respect to hd.

Note: We use the short form of horizontal distance of each node as hd.

Below is the implementation in Java:

import java.util.Queue;
import java.util.TreeMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
 
// class to create a node
class Node {
    int data;
    Node left, right;
 
    public Node(int data) {
        this.data = data;
        left = null;
        right = null;
    }
}

class NodeObj    // Each Object holds the current node to add in Queue
{
            Node node;
            int hd; // Horizontal Distance of each Node
 
            NodeObj(Node node, int hd) 
            {
                this.node = node;
                this.hd = hd;
            }
    
}
 
// class of binary tree
public class Tree 
{
    Node root;
     
    // method to print the topView of the binary tree
    void TopView(Node root) 
    {
        if (root == null)
        return;   // There is no top view of of a tree having  root null 
        
        Queue<NodeObj> queue = new LinkedList<NodeObj>();
        // Declare Map to maintain hd and node data.
        Map<Integer,Integer> topView = new TreeMap<>();
 
        // We first add the root into the queue along with it's hd 0.
        queue.add(new NodeObj(root, 0));
 
         
        // Standard level order traversal using Queue
        while (!queue.isEmpty()) 
        {
            NodeObj curr = queue.poll(); // we dequeue the curent NodeObj
            Node tempNode=curr.node; // get the current node to process.
            int hd=curr.hd;          // get the node's respective horizontal distance.
            
            // if our map does not contain the current node's hd we insert it.
            if (!topView.containsKey(hd)) 
            {
                topView.put(hd,tempNode.data);
            }
            
            // Now add the left and right child of each node 
            // to continue level order traversal
            
            if (tempNode.left != null) 
            {
                // hd of left child = hd of parent node - 1.
                queue.add(new NodeObj(tempNode.left, hd - 1)); 
            }
            
            if (tempNode.right != null) 
            {
                // hd of right child = hd of parent node + 1.
                queue.add(new NodeObj(tempNode.right, hd + 1));
            }
 
        }
        // We just print the values corresponding to each key(hd) or the nodes present in top view 
        for (Entry<Integer, Integer> entry : topView.entrySet()) {
            System.out.print(entry.getValue()+" ");
        }
    }
     
    // Driver Code or Main method to test above functions
    public static void main(String[] args) 
    { 
       
        Tree tree = new Tree();
        tree.root = new Node(20);
        tree.root.left = new Node(10);
        tree.root.left.left = new Node(5);
        tree.root.left.right = new Node(15);
        tree.root.right = new Node(30);
        tree.root.right.left = new Node(25);
        tree.root.right.right = new Node(35);
        
        System.out.println("The Top View of Binary Tree is: ");  
        
        tree.TopView(tree.root); 
    } 
     
}

Output:

The Top View of Binary Tree is: 
5 10 20 30 35

Time Complexity: Now we analyze the time complexity of our approach. We do a level order traversal of all the nodes in O (n). Along with this, and each insertion in our Tree-Map takes O (log n) time. So the Overall time Complexity will be O (n*log n).

Space Complexity: The Queue we use to implement the level order traversal will at the most store the nodes present at all levels and if we are given a skewed binary tree then it will store nodes at all levels so the overall space complexity is O (n).

That’s it for the Top View of Binary tree you can try this approach and run the code in your IDE or Java compiler.

You can ask your queries in the comment section below.

The post Top View of Binary Tree in Java appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/3rUoxaY

Comments

Popular posts from this blog

Difference between Web Designer and Web Developer Neeraj Mishra The Crazy Programmer

Have you ever wondered about the distinctions between web developers’ and web designers’ duties and obligations? You’re not alone! Many people have trouble distinguishing between these two. Although they collaborate to publish new websites on the internet, web developers and web designers play very different roles. To put these job possibilities into perspective, consider the construction of a house. To create a vision for the house, including the visual components, the space planning and layout, the materials, and the overall appearance and sense of the space, you need an architect. That said, to translate an idea into a building, you need construction professionals to take those architectural drawings and put them into practice. Image Source In a similar vein, web development and design work together to create websites. Let’s examine the major responsibilities and distinctions between web developers and web designers. Let’s get going, shall we? What Does a Web Designer Do?

A guide to data integration tools

CData Software is a leader in data access and connectivity solutions. It specializes in the development of data drivers and data access technologies for real-time access to online or on-premise applications, databases and web APIs. The company is focused on bringing data connectivity capabilities natively into tools organizations already use. It also features ETL/ELT solutions, enterprise connectors, and data visualization. Matillion ’s data transformation software empowers customers to extract data from a wide number of sources, load it into their chosen cloud data warehouse (CDW) and transform that data from its siloed source state, into analytics-ready insights – prepared for advanced analytics, machine learning, and artificial intelligence use cases. Only Matillion is purpose-built for Snowflake, Amazon Redshift, Google BigQuery, and Microsoft Azure, enabling businesses to achieve new levels of simplicity, speed, scale, and savings. Trusted by companies of all sizes to meet

2022: The year of hybrid work

Remote work was once considered a luxury to many, but in 2020, it became a necessity for a large portion of the workforce, as the scary and unknown COVID-19 virus sickened and even took the lives of so many people around the world.  Some workers were able to thrive in a remote setting, while others felt isolated and struggled to keep up a balance between their work and home lives. Last year saw the availability of life-saving vaccines, so companies were able to start having the conversation about what to do next. Should they keep everyone remote? Should they go back to working in the office full time? Or should they do something in between? Enter hybrid work, which offers a mix of the two. A Fall 2021 study conducted by Google revealed that over 75% of survey respondents expect hybrid work to become a standard practice within their organization within the next three years.  Thus, two years after the world abruptly shifted to widespread adoption of remote work, we are declaring 20