// Java implementation for Bottom View of Tree
// using Recursion
import java.util.ArrayList;
import java.util.Collections;
class Node {
int data;
Node left;
Node right;
Node(int x) {
data = x;
left = right = null;
}
}
// Class to generate bottom view of binary tree
class GfG {
// Function to generate bottom view of binary tree
static void Bottom(Node root, ArrayList<Integer> arr,
ArrayList<Integer> arr2, int[] left,
int[] right, int x, int p, int mid) {
// Base case
if (root == null) return;
// Update leftmost and rightmost value of x
if (x < left[0]) left[0] = x;
if (x > right[0]) right[0] = x;
// Check if arr is empty at mid+x
if (arr.get(mid + x) == Integer.MIN_VALUE) {
// Insert data of Node at arr[mid+x]
arr.set(mid + x, root.data);
// Insert priority of that
// Node at arr2[mid+x]
arr2.set(mid + x, p);
}
// If not empty and priority of previously
// inserted Node is less than current
else if (arr2.get(mid + x) < p) {
// Insert current Node data at arr[mid+x]
arr.set(mid + x, root.data);
// Insert priority of that Node at arr2[mid + x]
arr2.set(mid + x, p);
}
// Go right first then left
Bottom(root.right, arr, arr2, left,
right, x + 1, p + 1, mid);
Bottom(root.left, arr, arr2, left,
right, x - 1, p + 1, mid);
}
static int countNodes(Node root) {
if (root == null) {
return 0;
}
return 1 + countNodes(root.left)
+ countNodes(root.right);
}
// Utility function to generate bottom
// view of a binary tree
static ArrayList<Integer> bottomView(Node root) {
int n = countNodes(root);
ArrayList<Integer> arr = new ArrayList<>(2 * n + 1);
ArrayList<Integer> arr2 = new ArrayList<>(2 * n + 1);
// Initialize the array lists with Integer.MIN_VALUE
for (int i = 0; i < 2 * n + 1; i++) {
arr.add(Integer.MIN_VALUE);
arr2.add(Integer.MIN_VALUE);
}
// Leftmost horizontal distance
int[] left = new int[1];
left[0] = 0;
// Rightmost horizontal distance
int[] right = new int[1];
right[0] = 0;
int mid = n, x = 0, p = 0;
Bottom(root, arr, arr2, left, right, x, p, mid);
ArrayList<Integer> ans = new ArrayList<>();
// Store the bottom view from leftmost to rightmost
for (int i = mid + left[0]; i <= mid + right[0]; i++) {
if (arr.get(i) != Integer.MIN_VALUE) {
ans.add(arr.get(i));
}
}
return ans;
}
public static void main(String[] args) {
// Representation of the input tree:
// 1
// \
// 2
// \
// 4
// / \
// 3 5
Node root = new Node(1);
root.right = new Node(2);
root.right.right = new Node(4);
root.right.right.left = new Node(3);
root.right.right.right = new Node(5);
ArrayList<Integer> result = bottomView(root);
for (int val : result) {
System.out.print(val + " ");
}
}
}