×

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

Armstrong Number Program in Java

Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are...

6 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 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.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.

Java Write File

In this post, we'll examine various Java programming methods for writing into files. Since this class is character-oriented due to how it is used in file handling in Java, it...

4 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.