Open In App

Sum of nodes in bottom view of Binary Tree

Last Updated : 28 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a binary tree, the task is to return the sum of nodes in the bottom view of the given Binary Tree. The bottom view of a binary tree is the set of nodes visible when the tree is viewed from the bottom. 

Note: If there are multiple bottom-most nodes for a horizontal distance from the root, then the latter one in the level traversal is considered.

Examples: 

Example1: Sum of nodes in bottom view of Below Binary Tree [5, 10, 14, 4, 25] is 58 as 3 is not considered in the bottom view as 4 is present at same horizontal distance, so latter one is considered.

sum-of-nodes-in-bottom-view-of-binary-tree


Example2: Sum of nodes in bottom view of Below Binary Tree [4, 2, 5, 3, 6] is 20.

sum-of-nodes-in-bottom-view-of-binary-tree-2

[Expected Approach – 1] Using Level-Order Traversal – O(nlogn) Time and O(n) Space

The idea is to perform a level-order traversal while tracking each node’s horizontal distance (HD) from the root, similar to the bottom view. Starting with the root at HD equals 0, left children have HD – 1 and right children have HD + 1. We use a queue to process nodes level by level, updating a map with the sum of node values at each corresponding HD. Each node’s value is added to the sum of its HD to represent the cumulative sum of nodes at that level. By tracking the minimum and maximum HDs during traversal, we know the full range of HDs. After traversal, we extract the sum of nodes from the map in order of their HDs, which gives us the total sum for the bottom view of the tree.

Below is the implementation of the above approach:

C++
// C++ code to find the sum of the bottom view 
// using level-order traversal
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Function to return the sum of the bottom view 
// of the binary tree
int bottomViewSum(Node *root) {
    if (!root) return 0;

    // Map to store the last node at each 
    // horizontal distance (HD)
    map<int, int> hdMap;
    
    // Queue to store nodes and their HD
    queue<pair<Node*, int>> q;
    
    // Start level order traversal
  	// with root at HD 0
    q.push({root, 0});
    
    while (!q.empty()) {
      
        // Get current node and its HD
        Node *curr = q.front().first;
        int hd = q.front().second;
        q.pop();
        
        // Update the map with the 
      	// current node's data
        hdMap[hd] = curr->data;
        
        // Traverse the left subtree, HD - 1
        if (curr->left) {
            q.push({curr->left, hd - 1});
        }
        
        // Traverse the right subtree, HD + 1
        if (curr->right) {
            q.push({curr->right, hd + 1});
        }
    }
    
    // Calculate the sum of the 
  	// bottom view nodes
    int sum = 0;
    for (auto it : hdMap) {
        sum += it.second;
    }
    
    return sum;
}

int main() {
  
    // Representation of the input tree:
    //       20
    //      /  \
    //     8   22
    //    / \    \
    //   5   3   25
    //      / \
    //     10 14
    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->left->right->left = new Node(10);
    root->left->right->right = new Node(14);
    root->right->right = new Node(25);

    int sum = bottomViewSum(root);
    
    cout << sum << endl;
    
    return 0;
}
Java Python C# JavaScript

Output
57

[Expected Approach – 2] Using Depth-First Search – O(nlogn) Time and O(n) Space

Create a map where the key is the horizontal distance, and the value is a pair (sum, height) where sum is the cumulative sum of the node values at that horizontal distance, and height is the height of the last node seen at that distance. 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’s height with the existing one in the map, and if the new node’s height is greater, update the sum for that horizontal distance.

Below is the implementation of above approach:

C++
// C++ code to find the sum of the bottom view 
// using depth-first search (DFS)
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node *left, *right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Helper function to perform DFS and 
// update the bottom view
void dfs(Node* root, int hd, int depth, 
          map<int, pair<int, int>>& hdMap) {
    if (!root) return;

    // If this horizontal distance is  
    // being visited for the first time or 
    // we're at a deeper level, update it
    if (hdMap.find(hd) == hdMap.end() 
        || depth >= hdMap[hd].second) {
        hdMap[hd] = {root->data, depth};
    }

    // Traverse the left subtree with 
    // HD - 1 and increased depth
    dfs(root->left, hd - 1, depth + 1, hdMap);

    // Traverse the right subtree with 
    // HD + 1 and increased depth
    dfs(root->right, hd + 1, depth + 1, hdMap);
}

// Function to return the sum of the bottom view 
// of the binary tree using DFS
int bottomViewSum(Node *root) {
    if (!root) return 0;

    // Map to store the last node's data and its depth
    // at each horizontal distance (HD)
    map<int, pair<int, int>> hdMap;

    // Start DFS with root at HD 0 and depth 0
    dfs(root, 0, 0, hdMap);
    
    // Calculate the sum of the bottom view nodes
    int sumBottomView = 0;
    for (auto it : hdMap) {
        sumBottomView += it.second.first; 
    }
    
    return sumBottomView;
}

int main() {
  
    // Representation of the input tree:
    //       20
    //      /  \
    //     8   22
    //    / \    \
    //   5   3   25
    //      / \
    //     10 14
    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->left->right->left = new Node(10);
    root->left->right->right = new Node(14);
    root->right->right = new Node(25);

    int sumResult = bottomViewSum(root);
    
    cout << sumResult << endl;
    
    return 0;
}
Java Python C# JavaScript

Output
57


Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg