Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Bottom View Of Binary Tree

Moderate
0/80
Average time to solve is 10m
109 upvotes
Asked in companies
OYOMicrosoftAmazon

Problem statement

You are given a 'Binary Tree'.


Return the bottom view of the binary tree.


Note :
1. A node will be in the bottom-view if it is the bottom-most node at its horizontal distance from the root. 

2. The horizontal distance of the root from itself is 0. The horizontal distance of the right child of the root node is 1 and the horizontal distance of the left child of the root node is -1. 

3. The horizontal distance of node 'n' from root = horizontal distance of its parent from root + 1, if node 'n' is the right child of its parent.

4. The horizontal distance of node 'n' from root = horizontal distance of its parent from the root - 1, if node 'n' is the left child of its parent.

5. If more than one node is at the same horizontal distance and is the bottom-most node for that horizontal distance, including the one which is more towards the right.


Example:
Input: Consider the given Binary Tree:

alt text

Output: 4 2 6 3 7

Explanation:
Below is the bottom view of the binary tree.

alt text

1 is the root node, so its horizontal distance = 0.
Since 2 lies to the left of 0, its horizontal distance = 0-1= -1
3 lies to the right of 0, its horizontal distance = 0+1 = 1
Similarly, horizontal distance of 4 = Horizontal distance of 2 - 1= -1-1=-2
Horizontal distance of 5 = Horizontal distance of 2 + 1=  -1+1 = 0
Horizontal distance of 6 = 1-1 =0
Horizontal distance of 7 = 1+1 = 2

The bottom-most node at a horizontal distance of -2 is 4.
The bottom-most node at a horizontal distance of -1 is 2.
The bottom-most node at a horizontal distance of 0 is 5 and 6. However, 6 is more towards the right, so 6 is included.
The bottom-most node at a horizontal distance of 1 is 3.
The bottom-most node at a horizontal distance of 2 is 7.

Hence, the bottom view would be 4 2 6 3 7


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The only line contains elements in the level order form. The line consists of values of nodes separated by a single space. In case a node is null, we take -1 in its place.

For example, the input for the tree depicted in the below image will be:

alt text

1
2 3
4 -1 5 6
-1 7 -1 -1 -1 -1
-1 -1

Explanation :
Level 1 :
The root node of the tree is 1

Level 2 :
Left child of 1 = 2
Right child of 1 = 3

Level 3 :
Left child of 2 = 4
Right child of 2 = null (-1)
Left child of 3 = 5
Right child of 3 = 6

Level 4 :
Left child of 4 = null (-1)
Right child of 4 = 7
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 6 = null (-1)
Right child of 6 = null (-1)

Level 5 :
Left child of 7 = null (-1)
Right child of 7 = null (-1)

The first not-null node(of the previous level) is treated as the parent of the first two nodes of the current level. The second not-null node (of the previous level) is treated as the parent node for the next two nodes of the current level and so on.

The input ends when all nodes at the last level are null(-1).

The sequence will be put together in a single line separated by a single space. Hence, for the above-depicted tree, the input will be given as:

1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1


Output Format:
Return an array representing the bottom view of the given binary tree.


Note :
You do not need to print anything; it has already been taken care of. Just implement the given function.

Sample input 1 :

1 2 3 -1 -1 5 6 7 8 -1 -1 -1 -1 -1 -1


Sample output 1 :

7 5 8 6


Explanation of sample input 1 :

Test case 1:

alt text

As shown in the above figure,

1 is the root node, so its horizontal distance = 0.
Since 2 lies to the left of 0, its horizontal distance = 0-1= -1
3 lies to the right of 0, its horizontal distance = 0+1 = 1
Similarly, horizontal distance of 5 = Horizontal distance of 3 - 1= 1-1= 0
Horizontal distance of 6 = Horizontal distance of 3 + 1=  1+1 = 2
Horizontal distance of 7 = 0-1 =-1
Horizontal distance of 8 = 0+1 = 1

The bottom-most node at a horizontal distance of -1 is 7.
The bottom-most node at a horizontal distance of 0 is 5.
The bottom-most node at a horizontal distance of 1 is 8.
The bottom-most node at a horizontal distance of 2 is 6.

Hence, the bottom view would be 7 5 8 6.


Sample input 2 :

1 2 3 4 -1 6 7 -1 -1 -1 8 -1 -1 -1 -1 


Sample output 2 :

4 2 6 8 7


Expected Time Complexity:
Try to do this in O(n*log(n)).


Constraints:
1 <= n <= 10000

Where 'n' is the total number of nodes in the binary tree.

Time Limit: 1 sec
Hint

Use the horizontal distances and level of nodes to find the answer.

Approaches (3)
Recursive approach

The idea is to take two arrays and to store horizontal distance in one and priority of each node in another. The arrays are of size ‘2*N+1’(considering the worst case). On traversing the tree, if the current calculated horizontal distance is not present in the array, add it. Otherwise, compare the priority(stored in the second array) of the previously-stored value with the current one. If the priority of the new node is greater, update the value in the array.

  1. Take two vectors of size ‘2*N+1’ and initialize them to ‘INT_MAX’.
  2. Initialize variable ‘MID’ as ‘N’ which is the position of the root node in the arrays. Also, initialize the variables ‘HORIZONTAL_DISTANCE’ and ‘PRIORITY’ to 0.
  3. Take global variables ‘left’ and ‘right’, initialized to 0, denoting the size the nodes would take up in the arrays.
  4. Make a function call to ‘BOTTOM_VIEW’.
  5. In the function ‘BOTTOM_VIEW’,
        a. If the root is NULL, return.
        b. If the current horizontal distance is less than ‘LEFT’, update ‘LEFT’ to the value of horizontal distance.
        c. If the current horizontal distance is greater than ‘RIGHT’, update ‘RIGHT’ to the value of horizontal distance.
        d. If  ‘VEC[MID+HORIZONTAL_DISTANCE]’ is ‘INT_MIN’, that is, no node is present there, update ‘VEC[MID+HORIZONTAL_DISTANCE]’ to node’s data and ‘VEC[MID+HORIZONTAL_DISTANCE]’ to the current level number.
        e. Else if a node’s value is already present at position  ‘VEC[MID+HORIZONTAL_DISTANCE]’, compare the priorities array of both the nodes and store the node with bigger priority at that position.
        f. Recur for left subtree with ‘HORIZONTAL_DISTANCE-1’ and ‘PRIORITY+1’.
        g. Recur for the right subtree with ‘HORIZONTAL_DISTANCE+1’ and ‘PRIORITY+1’.
  6. Run a loop where ‘i’ ranges from ‘MID+LEFT’ to ‘MID+RIGHT’ and print all the values present in the first vector.
Time Complexity

O(N), where ‘N’ is the number of nodes present in the binary tree.

 

The binary tree is traversed once.

Space Complexity

O(2*N+1) ~ O(N), where ‘N’ is the number of nodes present in the binary tree.

 

In the worst case, two vectors of size ‘2*N+1’ are used to store horizontal distance and priority therefore, time complexity here grows by the O(N).

Code Solution
(100% EXP penalty)
Bottom View Of Binary Tree
All tags
Sort by
Search icon

Interview problems

Easy java solution || Using TreeMap and Pair class || beats 93% of users

import java.util.*;

 

class Pair<U, V> {

    public U first;

    public V second;

 

    public Pair(U first, V second) {

        this.first = first;

        this.second = second;

    }

}

 

public class Solution {

 

    private static List<Integer> getBottomView(TreeNode root) {

        List<Integer> ans = new ArrayList<>();

        

        if(root == null) {

            return ans;

        }

 

        Map<Integer, Integer> treeMap = new TreeMap<>();

        Queue<Pair<Integer, TreeNode>> pendingNodes = new LinkedList<>();

        pendingNodes.offer(new Pair<>(0, root));

 

        while(!pendingNodes.isEmpty()) {

            Pair<Integer, TreeNode> front = pendingNodes.poll();

 

            treeMap.put(front.first, front.second.val);

 

            if(front.second.left != null) {

                pendingNodes.offer(new Pair<>(front.first-1, front.second.left));

            }

 

            if(front.second.right != null) {

                pendingNodes.offer(new Pair<>(front.first+1, front.second.right));

            }

        }

 

        for(Map.Entry<Integer, Integer> entries: treeMap.entrySet()) {

            ans.add(entries.getValue());

        }

 

        return ans;

    }

    public static List<Integer> bottomView(TreeNode root) {

        // Write your code here. 

        return getBottomView(root);        

    }

}

1 view
0 replies
1 upvote

Interview problems

Bottom View Of Binary Tree || Easy C++ Solution || Using imaginary Vertical Lines

#include<bits/stdc++.h>
void solve(TreeNode<int>* node,vector<int>&ans,int lvl){
    queue<pair<TreeNode<int>*, int>> q;
    map<int,int>mpp;
    q.push({node,lvl});
    while(!q.empty()){
        auto it =q.front();
        q.pop();
        if(it.first->left){
          q.push({it.first->left, it.second- 1});
        }
        if(it.first->right){
            q.push({it.first->right,it.second+1});
        }
        mpp[it.second] =it.first->data;
    }
    for(auto it:mpp){
        ans.push_back(it.second);
    }
}


vector<int> bottomView(TreeNode<int> * root){
    vector<int>ans;
    int lvl =0;
    solve(root,ans,lvl);
    return ans;
}
19 views
0 replies
0 upvotes

Interview problems

Bottom View Of Binary Tree using Java

import java.util.*;

 

class TreeNodeWithHorizontalDistance {

    TreeNode node;

    int horizontalDistance;

 

    TreeNodeWithHorizontalDistance(TreeNode node, int horizontalDistance) {

        this.node = node;

        this.horizontalDistance = horizontalDistance;

    }

}

 

public class Solution {

    public static List<Integer> bottomView(TreeNode root) {

        if (root == null) return new ArrayList<>();

 

        List<Integer> bottomViewNodes = new ArrayList<>();

        Map<Integer, Integer> bottomViewMap = new TreeMap<>();

        Queue<TreeNodeWithHorizontalDistance> nodeQueue = new LinkedList<>();

 

        nodeQueue.add(new TreeNodeWithHorizontalDistance(root, 0));

 

        while (!nodeQueue.isEmpty()) {

            TreeNodeWithHorizontalDistance currentNodeWithHD = nodeQueue.poll();

            int horizontalDistance = currentNodeWithHD.horizontalDistance;

            TreeNode currentNode = currentNodeWithHD.node;

 

            bottomViewMap.put(horizontalDistance, currentNode.val);

 

            if (currentNode.left != null) {

                nodeQueue.add(new TreeNodeWithHorizontalDistance(currentNode.left, horizontalDistance - 1));

            }

 

            if (currentNode.right != null) {

                nodeQueue.add(new TreeNodeWithHorizontalDistance(currentNode.right, horizontalDistance + 1));

            }

        }

 

        for (Map.Entry<Integer, Integer> entry : bottomViewMap.entrySet()) {

            bottomViewNodes.add(entry.getValue());

        }

 

        return bottomViewNodes;        

    }

}

 

14 views
0 replies
0 upvotes

Interview problems

optimize in cpp 100%

vector<int> bottomView(TreeNode<int> * root) {

    vector<int> ans;

    if (root == NULL) {

        return ans;

    }

 

    map<int, int> bottomNode;

    queue<pair<TreeNode<int>*, int>> q;

 

    q.push(make_pair(root, 0));

 

    while (!q.empty()) {

        pair<TreeNode<int>*, int> temp = q.front();

        q.pop();

        TreeNode<int>* frontNode = temp.first;

        int hd = temp.second;

 

        bottomNode[hd] = frontNode->data;

 

        if (frontNode->left) {

            q.push(make_pair(frontNode->left, hd - 1));

        }

        if (frontNode->right) {

            q.push(make_pair(frontNode->right, hd + 1));

        }

    }

 

    for (auto i : bottomNode) {

        ans.push_back(i.second);

    }

 

    return ans;

}

 

18 views
0 replies
1 upvote

Interview problems

✅SIMPLE and EASY MAPPING APPROACH🔥🔥

#include<bits/stdc++.h>

 

vector<int> bottomView(TreeNode<int> * root){

    vector<int> ans;

    queue<pair<TreeNode<int>*,int>> q;

    map<int,int> mp;

 

    q.push({root,0});

 

    while(!q.empty()){

        TreeNode<int> *temp=q.front().first;

        int level=q.front().second;

        q.pop();

 

        if(mp.find(level)==mp.end()){

            mp[level]=temp->data;

        }

        if(mp.find(level)!=mp.end()){

            mp[level]=temp->data;

        }

 

        if(temp->left){

            q.push({temp->left,level-1});

        }

        if(temp->right){

            q.push({temp->right,level+1});

        }

 

    }

    for(auto &it:mp){

        ans.push_back(it.second);

    }

    return ans;

}

 

programming

10 views
0 replies
0 upvotes

Interview problems

Bottom View of Binary Tree with 100% Optimal Solution

#include<bits/stdc++.h>

vector<int> bottomView(TreeNode<int> * root){

    // Write your code here.

    vector<int> ans;

    if(root == NULL) return ans;

    map<int, int>mpp;

    queue<pair<TreeNode<int>*, int>> q;

    q.push({root,0});

    while(!q.empty()){

        auto it = q.front();

        q.pop();

        TreeNode<int>* node = it.first;

        int line = it.second;

        mpp[line] = node->data;

        if(node->left != NULL){

            q.push({node->left, line-1});

        }

        if(node->right != NULL){

            q.push({node->right,line+1});

        }

 

    }

    for(auto it: mpp){

        ans.push_back(it.second);

    }

    return ans;

}

17 views
0 replies
0 upvotes

Interview problems

Bottom View Solution✅✅

 



#include <map>
#include <vector>
using namespace std;
void code (TreeNode<int> *root,int level,int col,map<int,pair<int,int>> &mp)
{                                                   //col    level val
    if(root == NULL)
    return ;
    if (mp.find(col) == mp.end()) {
    mp[col].first = level;
    mp[col].second = root->data;
    } else {
    if (level >= mp[col].first) {
      mp[col].first = level;
      mp[col].second = root->data;
    }
    }
    code(root->left,level+1,col-1,mp);
    code(root->right,level+1,col+1,mp);
}
vector<int> bottomView(TreeNode<int> * root){
    map<int,pair<int,int>> mp;
    code(root,0,0,mp);
    vector<int>ans;
    for(auto it : mp)
    {
        ans.push_back(it.second.second);
    }
    return ans;
}

15 views
0 replies
0 upvotes

Interview problems

C++ solution

#include<bits/stdc++.h>

vector<int> bottomView(TreeNode<int> * root){

   map<int,int> nodes;

   queue<pair<TreeNode<int>*,pair<int,int>>> todo;

   todo.push({root,{0,0}});

   vector<int>ans;

   if(root==NULL) return ans;

   while(!todo.empty()){

       auto temp=todo.front();

       TreeNode<int>*Node=temp.first;

       todo.pop();

       int x=temp.second.first;

       int y=temp.second.second;

       nodes[x]=Node->data;

       if(Node->left){

           todo.push({Node->left,{x-1,y+1}});

       }

       if(Node->right){

           todo.push({Node->right,{x+1,y+1}});

       }

 

   }

   for(auto i:nodes){

       ans.push_back(i.second);

   }

   return ans;

}

 

30 views
0 replies
0 upvotes

Interview problems

Bottom View Python

 

def bottomView(root: BinaryTreeNode) -> List[int]:

    # Write your code here.

    bfs = []

    dicts = defaultdict(list)

    if root is None:

        return bfs

    queue = deque([(root, 0)])

 

    while(queue):

        l = len(queue)

        for i in range(0, l):

            curr, nl = queue.popleft()

            dicts[nl].append(curr.data)

            if curr.left:

                queue.append((curr.left, nl-1))

            if(curr.right):

                queue.append((curr.right, nl+1))

    dicts1 = sorted(dicts.items(), key=lambda x: x[0])

    for key, value in dicts1:

        bfs.append(value[-1])

    return bfs

    pass

 

6 views
0 replies
0 upvotes

Interview problems

Bottom view of binary tree | Easy c++ solution of striver sheet a to z dsa

 

#include<bits/stdc++.h>

vector<int> bottomView(TreeNode<int> * root){

    vector<int>ans;

    if(root == NULL) return ans;

 

    map <int, map<int,vector<int>>> nodes;

 

    // to fulfill this "If two nodes have the same position, then the value of the node that is added first will be the value that is on the left side."

    // we will use level order traversal

 

    queue< pair< TreeNode<int>*, pair<int,int>>> q;

 

    q.push({root,{0,0}});

 

    while(!q.empty()){

        pair< TreeNode<int>*, pair<int,int>> temp = q.front();

        q.pop();

        TreeNode<int>* frontNode = temp.first;

        int hd = temp.second.first; // hd = horizontal distance

        int lvl = temp.second.second; // lvl = level of node 

 

        if(frontNode!= NULL){

            nodes[hd][lvl].push_back(frontNode->data);

        }

 

        if(frontNode->left)

        q.push({frontNode ->left,{hd-1,lvl+1}});

        if(frontNode->right)

        q.push({frontNode ->right,{hd+1,lvl+1}});

    }

 

    for(auto i:nodes){ // <int,map<>>

        vector<int>temp;

        for(auto j : i.second){ // <int, vector<>>

             

            temp = j.second;

        }

        ans.push_back(temp[temp.size()-1]);

    }

}

beginners

programming

tutorial

datastructures

+1 more
48 views
0 replies
0 upvotes
Full screen
Console