Skip to content
Related Articles

Related Articles

Improve Article
Sum of nodes in top view of binary tree
  • Difficulty Level : Medium
  • Last Updated : 02 Mar, 2021

Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, the task is to print the sum of nodes in top view.
Examples: 

Input: 
       1
      /  \
     2    3
    / \    \
   4   5    6

Output: 16

Input:
       1
      /  \
    2      3
      \   
        4  
          \
            5
             \
               6

Output: 12

Approach: The idea is to put nodes of same horizontal distance together. We do a level order traversal so that the topmost node at a horizontal node is visited before any other node of same horizontal distance below it and we keep summing up their values and store the result in variable sum. Hashing is used to check if a node at given horizontal distance is seen or not.
Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Structure of binary tree
struct Node {
    Node* left;
    Node* right;
    int hd;
    int data;
};
 
// Function to create a new node
Node* newNode(int key)
{
    Node* node = new Node();
    node->left = node->right = NULL;
    node->data = key;
    return node;
}
 
// Function that returns the sum of
// nodes in top view of binary tree
int SumOfTopView(Node* root)
{
    if (root == NULL)
        return 0;
 
    queue<Node*> q;
 
    map<int, int> m;
    int hd = 0;
 
    root->hd = hd;
 
    int sum = 0;
 
    // Push node and horizontal distance to queue
    q.push(root);
 
    while (q.size()) {
        hd = root->hd;
 
        // Count function returns 1 if the container
        // contains an element whose key is equivalent
        // to hd, or returns zero otherwise.
        if (m.count(hd) == 0) {
            m[hd] = root->data;
            sum += m[hd];
        }
        if (root->left) {
            root->left->hd = hd - 1;
            q.push(root->left);
        }
        if (root->right) {
            root->right->hd = hd + 1;
            q.push(root->right);
        }
        q.pop();
        root = q.front();
    }
 
    return sum;
}
 
// Driver code
int main()
{
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->right = newNode(4);
    root->left->right->right = newNode(5);
    root->left->right->right->right = newNode(6);
 
    cout << SumOfTopView(root);
 
    return 0;
}

Java




// Java implementation of the approach
import java.util.*;
class Sol
{
     
// Structure of binary tree
static class Node
{
    Node left;
    Node right;
    int hd;
    int data;
};
 
// Function to create a new node
static Node newNode(int key)
{
    Node node = new Node();
    node.left = node.right = null;
    node.data = key;
    return node;
}
 
// Function that returns the sum of
// nodes in top view of binary tree
static int SumOfTopView(Node root)
{
    if (root == null)
        return 0;
 
    Queue<Node> q = new LinkedList<Node>();
 
    Map<Integer,Integer> m = new HashMap<Integer,Integer>();
    int hd = 0;
 
    root.hd = hd;
 
    int sum = 0;
 
    // Push node and horizontal distance to queue
    q.add(root);
 
    while (q.size() > 0)
    {
        hd = root.hd;
 
        // Count function returns 1 if the container
        // contains an element whose key is equivalent
        // to hd, or returns zero otherwise.
        if (!m.containsKey(hd))
        {
            m.put(hd, root.data);
            sum += m.get(hd);
        }
        if (root.left != null)
        {
            root.left.hd = hd - 1;
            q.add(root.left);
        }
        if (root.right != null)
        {
            root.right.hd = hd + 1;
            q.add(root.right);
        }
        q.remove();
        if(q.size() > 0)
            root = q.peek();
    }
 
    return sum;
}
 
// Driver code
public static void main(String args[])
{
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.right = newNode(4);
    root.left.right.right = newNode(5);
    root.left.right.right.right = newNode(6);
 
    System.out.print(SumOfTopView(root));
}
}
 
// This code is contributed by Arnab Kundu

Python3




# Python3 implementation of the approach
from collections import defaultdict
 
class Node:
     
    def __init__(self, key):
        self.data = key
        self.hd = None
        self.left = None
        self.right = None
 
# Function that returns the sum of
# nodes in top view of binary tree
def SumOfTopView(root):
 
    if root == None:
        return 0
 
    q = []
 
    m = defaultdict(lambda:0)
    hd, Sum = 0, 0
 
    root.hd = hd
 
    # Push node and horizontal
    # distance to queue
    q.append(root)
 
    while len(q) > 0:
        hd = root.hd
 
        # Count function returns 1 if
        # the container contains an
        # element whose key is equivalent
        # to hd, or returns zero otherwise.
        if m[hd] == 0:
            m[hd] = root.data
            Sum += m[hd]
         
        if root.left != None:
            root.left.hd = hd - 1
            q.append(root.left)
         
        if root.right != None:
            root.right.hd = hd + 1
            q.append(root.right)
         
        q.pop(0)
        if len(q) > 0:
            root = q[0]
     
    return Sum
 
# Driver code
if __name__ == "__main__":
 
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.right = Node(4)
    root.left.right.right = Node(5)
    root.left.right.right.right = Node(6)
 
    print(SumOfTopView(root))
 
# This code is contributed by Rituraj Jain

C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
     
// Structure of binary tree
public class Node
{
    public Node left;
    public Node right;
    public int hd;
    public int data;
};
 
// Function to create a new node
static Node newNode(int key)
{
    Node node = new Node();
    node.left = node.right = null;
    node.data = key;
    return node;
}
 
// Function that returns the sum of
// nodes in top view of binary tree
static int SumOfTopView(Node root)
{
    if (root == null)
        return 0;
 
    Queue<Node> q = new Queue<Node>();
 
    Dictionary<int,
               int> m = new Dictionary<int,
                                       int>();
    int hd = 0;
 
    root.hd = hd;
 
    int sum = 0;
 
    // Push node and horizontal distance to queue
    q.Enqueue(root);
 
    while (q.Count > 0)
    {
        hd = root.hd;
 
        // Count function returns 1 if the container
        // contains an element whose key is equivalent
        // to hd, or returns zero otherwise.
        if (!m.ContainsKey(hd))
        {
            m.Add(hd, root.data);
            sum += m[hd];
        }
         
        if (root.left != null)
        {
            root.left.hd = hd - 1;
            q.Enqueue(root.left);
        }
         
        if (root.right != null)
        {
            root.right.hd = hd + 1;
            q.Enqueue(root.right);
        }
        q.Dequeue();
        if(q.Count > 0)
            root = q.Peek();
    }
    return sum;
}
 
// Driver code
public static void Main(String []args)
{
    Node root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.left.right = newNode(4);
    root.left.right.right = newNode(5);
    root.left.right.right.right = newNode(6);
 
    Console.Write(SumOfTopView(root));
}
}
 
// This code is contributed by Princi Singh
Output: 
12

 

Time Complexity: O(N)

Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live 




My Personal Notes arrow_drop_up
Recommended Articles
Page :