Bottom View of a Binary Tree
Given a Binary Tree, The task is to print the bottom view from left to right. A node x is there in output if x is the bottommost node at its horizontal distance. The horizontal distance of the left child of a node x is equal to a horizontal distance of x minus 1, and that of a right child is the horizontal distance of x plus 1.
Examples:
Input: 20
/ \
8 22
/ \ \
5 3 25
/ \
10 14Output: 5, 10, 3, 14, 25.
Input: 20
/ \
8 22
/ \ / \
5 3 4 25
/ \
10 14
Output: 5 10 4 14 25.
Explanation: If there are multiple bottom-most nodes for a horizontal distance from the root, then print the later one in the level traversal. 3 and 4 are both the bottom-most nodes at a horizontal distance of 0, we need to print 4.
Bottom View of a Binary Tree Using level order traversal:
Store tree nodes in a queue for the level order traversal. Start with the horizontal distance hd as 0 of the root node, Using a Map which stores key-value pairs sorted by key and keep on adding a left child to the queue along with the horizontal distance as hd-1 and the right child as hd+1.
Every time a new horizontal distance or an existing horizontal distance is encountered put the node data for the horizontal distance as the key. For the first time it will add it to the map, next time it will replace the value. This will make sure that the bottom-most element for that horizontal distance is present on the map and if you see the tree from beneath that you will see that element. At last traverse the keys of map and print their respective values.
The following are steps to print the Bottom View of the Binary Tree.
- Initialize variable hd = 0,map m with int-int key value pair and queue q to store nodes level-wise.
- Set root->hd = hd and push root in q
- Run a while loop till q is empty
- Store the front element in node temp and temp ->hd in variable hd and pop it then set temp->data as value for key hd in m i.e. m[hd] = temp->data.
- If temp -> left is not NULL and set temp->left->hd = hd-1 as well as If temp -> right is not NULL and set temp->right->hd = hd+1 respectively.
- Iterate over the keys and print the values.
Below is the implementation of the above:
C++
// C++ Program to print Bottom View of Binary Tree #include<bits/stdc++.h> using namespace std; // Tree node class struct Node { int data; //data of the node int hd; //horizontal distance of the node Node *left, *right; //left and right references // Constructor of tree node Node( int key) { data = key; hd = INT_MAX; left = right = NULL; } }; // Method that prints the bottom view. void bottomView(Node *root) { if (root == NULL) return ; // Initialize a variable 'hd' with 0 // for the root element. int hd = 0; // TreeMap which stores key value pair // sorted on key value map< int , int > m; // Queue to store tree nodes in level // order traversal queue<Node *> q; // Assign initialized horizontal distance // value to root node and add it to the queue. root->hd = hd; q.push(root); // In STL, push() is used enqueue an item // Loop until the queue is empty (standard // level order loop) while (!q.empty()) { Node *temp = q.front(); q.pop(); // In STL, pop() is used dequeue an item // Extract the horizontal distance value // from the dequeued tree node. hd = temp->hd; // Put the dequeued tree node to TreeMap // having key as horizontal distance. Every // time we find a node having same horizontal // distance we need to replace the data in // the map. m[hd] = temp->data; // If the dequeued node has a left child, add // it to the queue with a horizontal distance hd-1. if (temp->left != NULL) { temp->left->hd = hd-1; q.push(temp->left); } // If the dequeued node has a right child, add // it to the queue with a horizontal distance // hd+1. if (temp->right != NULL) { temp->right->hd = hd+1; q.push(temp->right); } } // Traverse the map elements using the iterator. for ( auto i = m.begin(); i != m.end(); ++i) cout << i->second << " " ; } // Driver Code int main() { Node *root = new Node(20); root->left = new Node(8); root->right = new Node(22); root->left->left = new Node(5); root->left->right = new Node(3); root->right->left = new Node(4); root->right->right = new Node(25); root->left->right->left = new Node(10); root->left->right->right = new Node(14); cout << "Bottom view of the given binary tree :\n" ; bottomView(root); return 0; } |
Java
// Java Program to print Bottom View of Binary Tree import java.util.*; import java.util.Map.Entry; // Tree node class class Node { int data; //data of the node int hd; //horizontal distance of the node Node left, right; //left and right references // Constructor of tree node public Node( int key) { data = key; hd = Integer.MAX_VALUE; left = right = null ; } } //Tree class class Tree { Node root; //root node of tree // Default constructor public Tree() {} // Parameterized tree constructor public Tree(Node node) { root = node; } // Method that prints the bottom view. public void bottomView() { if (root == null ) return ; // Initialize a variable 'hd' with 0 for the root element. int hd = 0 ; // TreeMap which stores key value pair sorted on key value Map<Integer, Integer> map = new TreeMap<>(); // Queue to store tree nodes in level order traversal Queue<Node> queue = new LinkedList<Node>(); // Assign initialized horizontal distance value to root // node and add it to the queue. root.hd = hd; queue.add(root); // Loop until the queue is empty (standard level order loop) while (!queue.isEmpty()) { Node temp = queue.remove(); // Extract the horizontal distance value from the // dequeued tree node. hd = temp.hd; // Put the dequeued tree node to TreeMap having key // as horizontal distance. Every time we find a node // having same horizontal distance we need to replace // the data in the map. map.put(hd, temp.data); // If the dequeued node has a left child add it to the // queue with a horizontal distance hd-1. if (temp.left != null ) { temp.left.hd = hd- 1 ; queue.add(temp.left); } // If the dequeued node has a right child add it to the // queue with a horizontal distance hd+1. if (temp.right != null ) { temp.right.hd = hd+ 1 ; queue.add(temp.right); } } // Extract the entries of map into a set to traverse // an iterator over that. Set<Entry<Integer, Integer>> set = map.entrySet(); // Make an iterator Iterator<Entry<Integer, Integer>> iterator = set.iterator(); // Traverse the map elements using the iterator. while (iterator.hasNext()) { Map.Entry<Integer, Integer> me = iterator.next(); System.out.print(me.getValue()+ " " ); } } } // Main driver class public class BottomView { public static void main(String[] args) { Node root = new Node( 20 ); root.left = new Node( 8 ); root.right = new Node( 22 ); root.left.left = new Node( 5 ); root.left.right = new Node( 3 ); root.right.left = new Node( 4 ); root.right.right = new Node( 25 ); root.left.right.left = new Node( 10 ); root.left.right.right = new Node( 14 ); Tree tree = new Tree(root); System.out.println( "Bottom view of the given binary tree:" ); tree.bottomView(); } } |
Python3
# Python3 program to print Bottom # View of Binary Tree # deque supports efficient pish and pop on both ends from collections import deque # Tree node class class Node: def __init__( self , key): self .data = key self .hd = float ( 'inf' ) self .left = None self .right = None # Method that prints the bottom view. def bottomView(root): if (root = = None ): return # Initialize a variable 'hd' with 0 # for the root element. hd = 0 # Store minimum and maximum horizontal distance # so that we do not have to sort keys at the end min_hd, max_hd = 0 , 0 hd_dict = dict () # Queue to store tree nodes in level # order traversal q = deque() # Assign initialized horizontal distance # value to root node and add it to the queue. root.hd = hd q.append(root) # Loop until the queue is empty (standard # level order loop) while q: curr_node = q.popleft() # Extract the horizontal distance value # from the dequeued tree node. hd = curr_node.hd # Update the minimum and maximum hd min_hd = min (min_hd, hd) max_hd = max (max_hd, hd) # Put the dequeued tree node to dictionary # having key as horizontal distance. Every # time we find a node having same horizontal # distance we need to update the value in # the map. hd_dict[hd] = curr_node.data # If the dequeued node has a left child, add # it to the queue with a horizontal distance hd-1. if curr_node.left: curr_node.left.hd = hd - 1 q.append(curr_node.left) # If the dequeued node has a right child, add # it to the queue with a horizontal distance # hd+1. if curr_node.right: curr_node.right.hd = hd + 1 q.append(curr_node.right) # Traverse the map from least horizontal distance to # most horizontal distance. for i in range (min_hd, max_hd + 1 ): print (hd_dict[i], end = ' ' ) # Driver Code if __name__ = = '__main__' : root = Node( 20 ) root.left = Node( 8 ) root.right = Node( 22 ) root.left.left = Node( 5 ) root.left.right = Node( 3 ) root.right.left = Node( 4 ) root.right.right = Node( 25 ) root.left.right.left = Node( 10 ) root.left.right.right = Node( 14 ) print ( "Bottom view of the given binary tree :" ) bottomView(root) # This code is contributed by rutvik_56 |
C#
// C# program to print Bottom View of Binary Tree using System; using System.Collections; using System.Collections.Generic; // Tree node class class Node { // Data of the node public int data; // Horizontal distance of the node public int hd; // left and right references public Node left, right; // Constructor of tree node public Node( int key) { data = key; hd = 1000000; left = right = null ; } } // Tree class class Tree { // Root node of tree Node root; // Default constructor public Tree(){} // Parameterized tree constructor public Tree(Node node) { root = node; } // Method that prints the bottom view. public void bottomView() { if (root == null ) return ; // Initialize a variable 'hd' with // 0 for the root element. int hd = 0; // TreeMap which stores key value // pair sorted on key value SortedDictionary< int , int > map = new SortedDictionary< int , int >(); // Queue to store tree nodes in level order // traversal Queue queue = new Queue(); // Assign initialized horizontal distance // value to root node and add it to the queue. root.hd = hd; queue.Enqueue(root); // Loop until the queue is empty // (standard level order loop) while (queue.Count != 0) { Node temp = (Node) queue.Dequeue(); // Extract the horizontal distance value // from the dequeued tree node. hd = temp.hd; // Put the dequeued tree node to TreeMap // having key as horizontal distance. // Every time we find a node having same // horizontal distance we need to replace // the data in the map. map[hd] = temp.data; // If the dequeued node has a left child // add it to the queue with a horizontal // distance hd-1. if (temp.left != null ) { temp.left.hd = hd - 1; queue.Enqueue(temp.left); } // If the dequeued node has a right // child add it to the queue with a // horizontal distance hd+1. if (temp.right != null ) { temp.right.hd = hd + 1; queue.Enqueue(temp.right); } } foreach ( int i in map.Values) { Console.Write(i + " " ); } } } public class BottomView{ // Driver code public static void Main( string [] args) { Node root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); Tree tree = new Tree(root); Console.WriteLine( "Bottom view of the " + "given binary tree:" ); tree.bottomView(); } } // This code is contributed by pratham76 |
Javascript
<script> // JavaScript program to print Bottom View of Binary Tree // Tree node class class Node { // Constructor of tree node constructor(key) { this .data = key; // Data of the node this .hd = 1000000; // Horizontal distance of the node this .left = null ; // left and right references this .right = null ; } } // Tree class class Tree { // Parameterized tree constructor constructor(node) { // Root node of tree this .root = node; } // Method that prints the bottom view. bottomView() { if ( this .root == null ) return ; // Initialize a variable 'hd' with // 0 for the root element. var hd = 0; // TreeMap which stores key value // pair sorted on key value var map = {}; // Queue to store tree nodes in level order // traversal var queue = []; // Assign initialized horizontal distance // value to root node and add it to the queue. this .root.hd = hd; queue.push( this .root); // Loop until the queue is empty // (standard level order loop) while (queue.length != 0) { var temp = queue.shift(); // Extract the horizontal distance value // from the dequeued tree node. hd = temp.hd; // Put the dequeued tree node to TreeMap // having key as horizontal distance. // Every time we find a node having same // horizontal distance we need to replace // the data in the map. map[hd] = temp.data; // If the dequeued node has a left child // add it to the queue with a horizontal // distance hd-1. if (temp.left != null ) { temp.left.hd = hd - 1; queue.push(temp.left); } // If the dequeued node has a right // child add it to the queue with a // horizontal distance hd+1. if (temp.right != null ) { temp.right.hd = hd + 1; queue.push(temp.right); } } for (const [key, value] of Object.entries(map).sort( (a, b) => a[0] - b[0] )) { document.write(value + " " ); } } } // Driver code var root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); var tree = new Tree(root); document.write( "Bottom view of the " + "given binary tree:<br>" ); tree.bottomView(); </script> |
Bottom view of the given binary tree : 5 10 4 14 25
Time Complexity: O(N * logN)
Auxiliary Space: O(N)
Bottom View of a Binary Tree Using Depth first search:
Create a map where the key is the horizontal distance and the value is a pair(a, b) where a is the value of the node and b is the height of the node. Perform a pre-order traversal of the tree. If the current node at a horizontal distance of h is the first we’ve seen, insert it into the map. Otherwise, compare the node with the existing one in map and if the height of the new node is greater, update the Map.
Follow the below steps to implement the idea:
Create a map where the key is the horizontal distance and the value is a pair(a, b) where a is the value of the node and b is the height of the node.
- Recursively apply Depth first search on the Tree starting from root node and keep a track of height curr and horizontal distance as hd of the current node with respect to root node as root node’s height is 0.
- If there’s no node as value for horizontal distance hd in map then set map[hd] = make_pair(root -> data, curr).
- Else store the pair value of mp[hd] in p. Then
- If p.second <= curr then set m[hd].second = curr and m[hd].first = root -> data
- Call depth first search for left node of root node with height curr + 1 and horizontal distance as hd – 1 and right node of root node with height curr + 1 and horizontal distance as hd + 1
- Base case would be to return when root is NULL.
Below is the implementation of the above approach.
C++
// C++ Program to print Bottom View of Binary Tree #include <bits/stdc++.h> #include <map> using namespace std; // Tree node class struct Node { // data of the node int data; // horizontal distance of the node int hd; //left and right references Node * left, * right; // Constructor of tree node Node( int key) { data = key; hd = INT_MAX; left = right = NULL; } }; void printBottomViewUtil(Node * root, int curr, int hd, map < int , pair < int , int >> & m) { // Base case if (root == NULL) return ; // If node for a particular // horizontal distance is not // present, add to the map. if (m.find(hd) == m.end()) { m[hd] = make_pair(root -> data, curr); } // Compare height for already // present node at similar horizontal // distance else { pair < int , int > p = m[hd]; if (p.second <= curr) { m[hd].second = curr; m[hd].first = root -> data; } } // Recur for left subtree printBottomViewUtil(root -> left, curr + 1, hd - 1, m); // Recur for right subtree printBottomViewUtil(root -> right, curr + 1, hd + 1, m); } void printBottomView(Node * root) { // Map to store Horizontal Distance, // Height and Data. map < int , pair < int , int > > m; printBottomViewUtil(root, 0, 0, m); // Prints the values stored by printBottomViewUtil() map < int , pair < int , int > > ::iterator it; for (it = m.begin(); it != m.end(); ++it) { pair < int , int > p = it -> second; cout << p.first << " " ; } } int main() { Node * root = new Node(20); root -> left = new Node(8); root -> right = new Node(22); root -> left -> left = new Node(5); root -> left -> right = new Node(3); root -> right -> left = new Node(4); root -> right -> right = new Node(25); root -> left -> right -> left = new Node(10); root -> left -> right -> right = new Node(14); cout << "Bottom view of the given binary tree :\n" ; printBottomView(root); return 0; } |
Java
// Java program to print Bottom View of Binary Tree import java.io.*; import java.lang.*; import java.util.*; class GFG{ // Tree node class static class Node { // Data of the node int data; // Horizontal distance of the node int hd; // Left and right references Node left, right; // Constructor of tree node public Node( int key) { data = key; hd = Integer.MAX_VALUE; left = right = null ; } } static void printBottomViewUtil(Node root, int curr, int hd, TreeMap<Integer, int []> m) { // Base case if (root == null ) return ; // If node for a particular // horizontal distance is not // present, add to the map. if (!m.containsKey(hd)) { m.put(hd, new int []{ root.data, curr }); } // Compare height for already // present node at similar horizontal // distance else { int [] p = m.get(hd); if (p[ 1 ] <= curr) { p[ 1 ] = curr; p[ 0 ] = root.data; } m.put(hd, p); } // Recur for left subtree printBottomViewUtil(root.left, curr + 1 , hd - 1 , m); // Recur for right subtree printBottomViewUtil(root.right, curr + 1 , hd + 1 , m); } static void printBottomView(Node root) { // Map to store Horizontal Distance, // Height and Data. TreeMap<Integer, int []> m = new TreeMap<>(); printBottomViewUtil(root, 0 , 0 , m); // Prints the values stored by printBottomViewUtil() for ( int val[] : m.values()) { System.out.print(val[ 0 ] + " " ); } } // Driver Code public static void main(String[] args) { Node root = new Node( 20 ); root.left = new Node( 8 ); root.right = new Node( 22 ); root.left.left = new Node( 5 ); root.left.right = new Node( 3 ); root.right.left = new Node( 4 ); root.right.right = new Node( 25 ); root.left.right.left = new Node( 10 ); root.left.right.right = new Node( 14 ); System.out.println( "Bottom view of the given binary tree:" ); printBottomView(root); } } // This code is contributed by Kingash |
Python3
# Python3 program to print Bottom # View of Binary Tree class Node: def __init__( self , key = None , left = None , right = None ): self .data = key self .left = left self .right = right def printBottomView(root): # Create a dictionary where # key -> relative horizontal distance # of the node from root node and # value -> pair containing node's # value and its level d = dict () printBottomViewUtil(root, d, 0 , 0 ) # Traverse the dictionary in sorted # order of their keys and print # the bottom view for i in sorted (d.keys()): print (d[i][ 0 ], end = " " ) def printBottomViewUtil(root, d, hd, level): # Base case if root is None : return # If current level is more than or equal # to maximum level seen so far for the # same horizontal distance or horizontal # distance is seen for the first time, # update the dictionary if hd in d: if level > = d[hd][ 1 ]: d[hd] = [root.data, level] else : d[hd] = [root.data, level] # recur for left subtree by decreasing # horizontal distance and increasing # level by 1 printBottomViewUtil(root.left, d, hd - 1 , level + 1 ) # recur for right subtree by increasing # horizontal distance and increasing # level by 1 printBottomViewUtil(root.right, d, hd + 1 , level + 1 ) # Driver Code if __name__ = = '__main__' : root = Node( 20 ) root.left = Node( 8 ) root.right = Node( 22 ) root.left.left = Node( 5 ) root.left.right = Node( 3 ) root.right.left = Node( 4 ) root.right.right = Node( 25 ) root.left.right.left = Node( 10 ) root.left.right.right = Node( 14 ) print ( "Bottom view of the given binary tree :" ) printBottomView(root) # This code is contributed by tusharroy |
C#
// C# program to print Bottom View of Binary Tree using System; using System.Collections; using System.Collections.Generic; // Tree node class public class Node { // data of the node public int data; // horizontal distance of the node public int hd; // left and right references public Node left, right; // Constructor of tree node public Node( int key) { data = key; hd = Int32.MaxValue; left = right = null ; } } public class BinaryTree { public static void printBottomViewUtil( Node root, int curr, int hd, SortedDictionary< int , Tuple< int , int > > m) { // Base case if (root == null ) return ; // If node for a particular // horizontal distance is not // present, add to the map. if (!m.ContainsKey(hd)) { m[hd] = Tuple.Create(root.data, curr); } // Compare height for already // present node at similar horizontal // distance else { Tuple< int , int > p = m[hd]; if (p.Item2 <= curr) { p = Tuple.Create(root.data, curr); } m[hd] = p; } // Recur for left subtree printBottomViewUtil(root.left, curr + 1, hd - 1, m); // Recur for right subtree printBottomViewUtil(root.right, curr + 1, hd + 1, m); } public static void printBottomView(Node root) { // Map to store Horizontal Distance, // Height and Data. SortedDictionary< int , Tuple< int , int > > m = new SortedDictionary< int , Tuple< int , int > >(); printBottomViewUtil(root, 0, 0, m); // Prints the values stored by printBottomViewUtil() foreach (KeyValuePair< int , Tuple< int , int > > it in m) { Tuple< int , int > p = it.Value; Console.Write(p.Item1 + " " ); } } // Driver Code public static void Main( string [] args) { Node root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); Console.WriteLine( "Bottom view of the given binary tree :" ); printBottomView(root); } } // This code is contributed by Tapesh (tapeshdua420) |
Javascript
class Node { constructor(key = null , left = null , right = null ) { this .data = key; this .left = left; this .right = right; } } function printBottomView(root) { // Create a dictionary where // key -> relative horizontal distance // of the node from root node and // value -> pair containing node's // value and its level const d = {}; printBottomViewUtil(root, d, 0, 0); // Traverse the dictionary in sorted // order of their keys and print // the bottom view for (const i of Object.keys(d).sort( function (a, b) { return a - b } )) { process.stdout.write(d[i][0] + " " ); } } function printBottomViewUtil(root, d, hd, level) { // Base case if (!root) { return ; } // If current level is more than or equal // to maximum level seen so far for the // same horizontal distance or horizontal // distance is seen for the first time, // update the dictionary if (hd in d) { if (level >= d[hd][1]) { d[hd] = [root.data, level]; } } else { d[hd] = [root.data, level]; } // recur for left subtree by decreasing // horizontal distance and increasing // level by 1 printBottomViewUtil(root.left, d, hd - 1, level + 1); // recur for right subtree by increasing // horizontal distance and increasing // level by 1 printBottomViewUtil(root.right, d, hd + 1, level + 1); } // Driver Code if (require.main === module) { const root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); console.log( "Bottom view of the given binary tree :" ); printBottomView(root); } // This code is contributed by phasing17. |
Bottom view of the given binary tree : 5 10 4 14 25
Time Complexity: O(N * logN) the extra logN factor is for accessing map
Auxiliary Space: O(N)
Bottom View of a Binary Tree Using unordered_map O(n):
Create a unordered_map where the key is the horizontal distance and the value is a int x, where x is the value of the node .Perform a level order traversal of the tree. For every node at a horizontal distance of h we will store its value in unordered_map<int,int> (eg <vertical_index , root->data> ).
suppose on a X plane.
… -2 -1 0 1 2 ……
. . 20 . .
. . / \ . .
. 8 22 .
. / . \ . \ .
5 . 3 . 25
. / \ .
10 14
Now we will perform level order traversal and for every node we visit we will store its vertical index and with value.
C++
#include <bits/stdc++.h> using namespace std; // Tree node class struct Node { // data of the node int data; // horizontal distance of the node int hd; //left and right references Node * left, * right; // Constructor of tree node Node( int key) { data = key; hd = INT_MAX; left = right = NULL; } }; void printBottomView(Node * root) { if (!root) return ; //if root is NULL unordered_map< int , int > hash; // <vertical_index , root->data> int leftmost = 0; // to store the leftmost index so that we move from left to right queue<pair<Node*, int >> q; // pair<Node*,vertical Index> for level order traversal. q.push({root,0}); // push the root and 0 vertial index while (!q.empty()){ auto top = q.front(); // store q.front() in top variable q.pop(); Node *temp = top.first; // store the Node in temp for left and right nodes int ind = top.second; // store the vertical index of current node hash[ind] = temp->data; // store the latest vertical_index(key) -> root->data(value) leftmost = min(ind,leftmost); // have the leftmost vertical index if (temp->left){ q.push({temp->left,ind-1});} // check if any node of left then go in negative direction if (temp->right){ q.push({temp->right,ind+1});} //check if any node of left then go in positive direction } //Traverse each value in hash from leftmost to positive side till key is available while (hash.find(leftmost)!=hash.end()){ cout<<hash[leftmost++]<< " " ; } } int main() { Node * root = new Node(20); root -> left = new Node(8); root -> right = new Node(22); root -> left -> left = new Node(5); root -> left -> right = new Node(3); root -> right -> left = new Node(4); root -> right -> right = new Node(25); root -> left -> right -> left = new Node(10); root -> left -> right -> right = new Node(14); cout << "Bottom view of the given binary tree :\n" ; printBottomView(root); return 0; } |
Java
// Java implementation of the above approach import java.util.*; class gfg2 { // Tree node class static class Node { // data of the node int data; // horizontal distance of the node int hd; // left and right references Node left, right; // Constructor of tree node Node( int key) { data = key; hd = Integer.MAX_VALUE; left = right = null ; } } static class pair { Node first; int second; pair(Node f, int s) { first = f; second = s; } } static void printBottomView(Node root) { if (root == null ) return ; // if root is NULL HashMap<Integer, Integer> hash = new HashMap<>(); // <vertical_index , // root->data> int leftmost = 0 ; // to store the leftmost index so // that we move from left to right Queue<pair> q = new ArrayDeque<>(); // pair<Node*,vertical // Index> for level order // traversal. q.add( new pair( root, 0 )); // push the root and 0 vertial index while (!q.isEmpty()) { pair top = q.peek(); // store q.front() in top // variable q.remove(); Node temp = top.first; // store the Node in temp for // left and right nodes int ind = top.second; // store the vertical // index of current node hash.put(ind, temp.data); // store the latest // vertical_index(key) -> // root->data(value) leftmost = Math.min( ind, leftmost); // have the leftmost // vertical index if (temp.left != null ) { q.add( new pair(temp.left, ind - 1 )); } // check if any node of left then go in // negative direction if (temp.right != null ) { q.add( new pair(temp.right, ind + 1 )); } // check if any node of left then go in // positive direction } // Traverse each value in hash from leftmost to // positive side till key is available while (hash.containsKey(leftmost)) { System.out.print( hash.getOrDefault(leftmost++, 0 ) + " " ); } } public static void main(String[] args) { Node root = new Node( 20 ); root.left = new Node( 8 ); root.right = new Node( 22 ); root.left.left = new Node( 5 ); root.left.right = new Node( 3 ); root.right.left = new Node( 4 ); root.right.right = new Node( 25 ); root.left.right.left = new Node( 10 ); root.left.right.right = new Node( 14 ); System.out.println( "Bottom view of the given binary tree :" ); printBottomView(root); } } // This code is contributed by karandeep1234 |
Python3
from collections import deque, defaultdict # Tree node class class Node: # data of the node def __init__( self , key): self .data = key # horizontal distance of the node self .hd = float ( "inf" ) #left and right references self .left = None self .right = None def printBottomView(root): if root is None : return #if root is NULL hash = defaultdict( lambda : 0 ) # <vertical_index , root->data> leftmost = 0 # to store the leftmost index so that we move from left to right q = deque() # pair<Node*,vertical Index> for level order traversal. q.append((root, 0 )) # push the root and 0 vertial index while q: top = q.popleft() # store q.front() in top variable temp, ind = top # store the Node in temp for left and right nodes and store the vertical index of current node hash [ind] = temp.data # store the latest vertical_index(key) -> root->data(value) leftmost = min (ind, leftmost) # have the leftmost vertical index if temp.left: q.append((temp.left, ind - 1 )) # check if any node of left then go in negative direction if temp.right: q.append((temp.right, ind + 1 )) #check if any node of left then go in positive direction #Traverse each value in hash from leftmost to positive side till key is available for i in range (leftmost, len ( hash )): if hash [i]: print ( hash [i], end = " " ) root = Node( 20 ) root.left = Node( 8 ) root.right = Node( 22 ) root.left.left = Node( 5 ) root.left.right = Node( 3 ) root.right.left = Node( 4 ) root.right.right = Node( 25 ) root.left.right.left = Node( 10 ) root.left.right.right = Node( 14 ) print ( "Bottom view of the given binary tree :" ) printBottomView(root) # This code is contributed by phasing17. |
C#
// C# implementation of the approach using System; using System.Collections; using System.Collections.Generic; class gfg { // Tree node class public class Node { // data of the node public int data; // horizontal distance of the node public int hd; // left and right references public Node left, right; // Constructor of tree node public Node( int key) { data = key; hd = Int32.MaxValue; left = right = null ; } } public class pair { public Node first; public int second; public pair(Node f, int s) { first = f; second = s; } } static void printBottomView(Node root) { if (root == null ) return ; // if root is NULL Dictionary< int , int > hash = new Dictionary< int , int >(); // root->data> int leftmost = 0; // to store the leftmost index so // that we move from left to right Queue<pair> q = new Queue<pair>(); // pair<Node*,vertical // Index> for level order // traversal. q.Enqueue( new pair( root, 0)); // push the root and 0 vertial index while (q.Count != 0) { pair top = q.Peek(); // store q.front() in top // variable q.Dequeue(); Node temp = top.first; // store the Node in temp for // left and right nodes int ind = top.second; // store the vertical // index of current node if (hash.ContainsKey(ind)) { hash.Remove(ind); hash.Add(ind, temp.data); } else hash.Add(ind, temp.data); // store the latest // vertical_index(key) -> // root->data(value) leftmost = Math.Min( ind, leftmost); // have the leftmost // vertical index if (temp.left != null ) { q.Enqueue( new pair(temp.left, ind - 1)); } // check if any node of left then go in // negative direction if (temp.right != null ) { q.Enqueue( new pair(temp.right, ind + 1)); } // check if any node of left then go in // positive direction } // Traverse each value in hash from leftmost to // positive side till key is available while (hash.ContainsKey(leftmost)) { Console.Write(hash[leftmost++] + " " ); } } public static void Main( string [] args) { Node root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); Console.WriteLine( "Bottom view of the given binary tree :" ); printBottomView(root); } } // This code is contributed by karandeep1234 |
Javascript
// Node class class Node { constructor(key) { this .data = key; this .hd = Infinity; this .left = null ; this .right = null ; } } function printBottomView(root) { if (!root) return ; //if root is NULL let hash = new Map(); // <vertical_index , root->data> let leftmost = 0; // to store the leftmost index so that we move from left to right let q = new Array(); // pair<Node*,vertical Index> for level order traversal. q.push([root, 0]); // push the root and 0 vertical index while (q.length) { let top = q.shift(); let temp = top[0], ind = top[1]; hash.set(ind, temp.data); // store the latest vertical_index(key) -> root->data(value) leftmost = Math.min(ind, leftmost); // have the leftmost vertical index if (temp.left) q.push([temp.left, ind - 1]); // check if any node of left then go in negative direction if (temp.right) q.push([temp.right, ind + 1]); //check if any node of left then go in positive direction } for (let i = leftmost; i < hash.size; i++) { if (hash.has(i)) { //Traverse each value in hash from leftmost to //positive side till key is available process.stdout.write(hash.get(i) + ' ' ); } } } // Driver code let root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); console.log( "Bottom view of the given binary tree:" ); printBottomView(root); |
Bottom view of the given binary tree : 5 10 4 14 25
Please Login to comment...