×

Bottom view of a binary tree in Java

The lowest nodes in their horizontal distance are present and referred to as the bottom view of a binary tree. The horizontal distance between the nodes of a binary tree is described as follows:

The horizontal length of the root is zero. The left child's horizontal distance equals its parent's horizontal distance minus one.

For the level order traversal, place tree nodes in a queue. Start with the root node's horizontal distance (hd) as 0, then add a left child to the line along with the horizontal distance (hd-1) and the correct child with the horizontal distance (hd+1).

Regarding the level order traversal, place tree nodes in a queue. Start with the root node's horizontal distance (hd) as 0, then add a left child to the line along with the horizontal distance (hd-1) and the correct child with the horizontal distance (hd+1).

Use the horizontal distance node data as the key whenever a new or existing horizontal distance is detected. It will first add it to the map before replacing the value the next time. This will guarantee that the piece at the bottom of that horizontal distance is visible on the map, so you will see it if you look at the Tree from below. Finally, go over the map's keys and publish their corresponding values.

Printing the Binary Tree's Bottom view involves the steps listed below.

  1. Set the variable hd to equal 0, map m with an int-int key-value pair, and queue q to level-wise store nodes.
  2. Push root in q and set root->hd = hd.
  3. While loop, continue till q is empty.
  4. Store the front element in the temp node, store the temp ->hd variable in the variable hd, pop it, and then set temp->data as the value for the hd key in the m variable, i.e. m[hd] = temp->data.
  5. If temp -> left is present and not NULL, set temp->left->hd to hd-1; likewise, if temp -> right is present and not NULL, put temp->right->hd to hd+1.
  6. Print the values after iterating through the keys.

BottomView.java

// Print the bottom View of the binary Tree using a Java program.
import java.util.*;
import java.util.Map.Entry;
// Tree node type
class Node
{
int data; // the node's data
int hd; // the node's horizontal distance
Node left, right; // allusions to the left and right.


// Builder of tree nodes
public Node (int key)
{
data = key;
hd = Integer.MAX_VALUE;
left = right = null;
}
}


// Tree type
class Tree
{
Node root; // root of the Tree
// Default constructor
public Tree() {}


// Parameterized tree constructor
public Tree(Node node)
{
root = node;
}


// a process for printing the bottom view.
public void bottomView()
{
if (root == null)
return;
// Set the root element's initial value for the variable "hd" to zero.
int hd = 0;
// TreeMap that organizes key-value pairs by key value
Map<Integer, Integer> map = new TreeMap<>();


//Tree node storage queue for level order traversal
Queue<Node> queue = new LinkedList<Node>();


// Give root the initialization value for the horizontal distance.
//Node and put it on the waiting list.
root.hd = hd;
queue.add(root);


// Continue until the wait is empty (standard level order loop)
while (!queue.isEmpty())
{
Node temp = queue.remove();


// Calculate the horizontal distance using the
// tree node in deque.
hd = temp.hd;


// Place the dequeued tree node in the TreeMap with the key.
// as horizontal separation. whenever we discover a node
// requiring replacement with the same horizontal distance
// information on the map.
map.put(hd, temp.data);


// Add the left child of the dequeued Node if it has one.
// a line with a hd-1 horizontal distance.
if (temp.left != null)
{
temp.left.hd = hd-1;
queue.add(temp.left);
}
// If the dequeued Node has the right child, add it to the
// a line with a hd-1 horizontal distance.
if (temp.right != null)
{
temp.right.hd = hd+1;
queue.add(temp.right);
}
}


// Extract the map's entries into a set and traverse it.
// over that, an iterator.
Set<Entry<Integer, Integer>> set = map.entrySet();


Iterator<Entry<Integer, Integer>> iterator = set.iterator();


//Utilize the iterator to navigate the map's elements.
while (iterator.hasNext())
{
Map.Entry<Integer, Integer> me = iterator.next();
System.out.print(me.getValue()+" ");
}
}
}
public class BottomView
{
public static void main(String[] args)
{
Node root = new Node(10);
root.left = new Node(7);
root.right = new Node(16);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(3);
root.right.right = new Node(22);
root.left.right.left = new Node(13);
root.left.right.right = new Node(12);
Tree tree = new Tree(root);
System.out.println("Bottom view of the given binary tree:");
tree.bottomView();
}
}

Output:

The bottom view of a binary tree is:
4 13 3 12 22

Related Topics

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A...

4 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

Java CountDownLatch

Another crucial classes for concurrent execution is CountDownLatch. It is a synchronisation tool that enables one or more threads to await until a series of tasks started by another thread...

4 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Add Time in Java

Before Java 8, java.util.Date was one of the most usually involved classes for addressing date-time values in java. Then Java 8 presented java.time.LocalDateTime and java.time.ZonedDateTime. Java 8 likewise permits us...

6 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Java String contains() method

contains() method returns true only if it contains the given sequence of characters otherwise it returns false. syntax: public boolean contains(CharSequence sequence) parameters: sequence : It is the sequence to be searched. Returns: It returns true...

1 minute read.

SHA Decrypt in Java

In this section, we will be acknowledged about the decryption of SHA in Java. Java SHA The SHA cryptographic hash algorithm in cryptography outputs the hash value as an approximately 40-digit-long hexadecimal...

4 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.