Open In App

Sum of nodes in the right view of the given binary tree

Given a binary tree, the task is to find the sum of the nodes which are visible in the right view. The right view of a binary tree is the set of nodes visible when the tree is viewed from the right.
Examples: 

Input:
1
/ \
2 3
/ \ \
4 5 6
Output: 10
1 + 3 + 6 = 10
Input:
1
/ \
2 3
\
4
\
5
\
6
Output: 19

Approach: The problem can be solved using simple recursive traversal. We can keep track of the level of a node by passing a parameter to all the recursive calls. The idea is to keep track of the maximum level also and traverse the tree in a manner that the right subtree is visited before the left subtree. Whenever a node whose level is more than the maximum level so far is encountered, add the value of the node to the sum because it is the last node in its level (Note that the right subtree is traversed before the left subtree).
Below is the implementation of the above approach:




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
class Node {
public:
    int data;
    Node *left, *right;
};
 
// A utility function to create
// a new Binary Tree Node
Node* newNode(int item)
{
    Node* temp = new Node();
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Recursive function to find the sum of nodes
// of the right view of the given binary tree
void sumRightViewUtil(Node* root, int level,
                      int* max_level, int* sum)
{
    // Base Case
    if (root == NULL)
        return;
 
    // If this is the last Node of its level
    if (*max_level < level) {
        *sum += root->data;
        *max_level = level;
    }
 
    // Recur for left and right subtrees
    sumRightViewUtil(root->right, level + 1, max_level, sum);
    sumRightViewUtil(root->left, level + 1, max_level, sum);
}
 
// A wrapper over sumRightViewUtil()
void sumRightView(Node* root)
{
    int max_level = 0;
    int sum = 0;
    sumRightViewUtil(root, 1, &max_level, &sum);
    cout << sum;
}
 
// Driver code
int main()
{
    Node* root = newNode(12);
    root->left = newNode(10);
    root->right = newNode(30);
    root->right->left = newNode(25);
    root->right->right = newNode(40);
 
    sumRightView(root);
 
    return 0;
}




// Java implementation of the approach
 
// Class for a node of the tree
class Node {
    int data;
    Node left, right;
 
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
class BinaryTree {
    Node root;
    static int max_level = 0;
    static int sum = 0;
 
    // Recursive function to find the sum of nodes
    // of the right view of the given binary tree
    void sumRightViewUtil(Node node, int level)
    {
        // Base Case
        if (node == null)
            return;
 
        // If this is the last node of its level
        if (max_level < level) {
            sum += node.data;
            max_level = level;
        }
 
        // Recur for left and right subtrees
        sumRightViewUtil(node.right, level + 1);
        sumRightViewUtil(node.left, level + 1);
    }
 
    // A wrapper over sumRightViewUtil()
    void sumRightView()
    {
 
        sumRightViewUtil(root, 1);
        System.out.print(sum);
    }
 
    // Driver code
    public static void main(String args[])
    {
 
        BinaryTree tree = new BinaryTree();
        tree.root = new Node(12);
        tree.root.left = new Node(10);
        tree.root.right = new Node(30);
        tree.root.right.left = new Node(25);
        tree.root.right.right = new Node(40);
 
        tree.sumRightView();
    }
}




# Python3 implementation of the approach
 
# A binary tree node
class Node:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
 
# Recursive function to find the sum of nodes
# of the right view of the given binary tree
def sumRightViewUtil(root, level, max_level, sum):
     
    # Base Case
    if root is None:
        return
 
    # If this is the last node of its level
    if (max_level[0] < level):
        sum[0]+= root.data
        max_level[0] = level
 
    # Recur for left and right subtree
    sumRightViewUtil(root.right, level + 1, max_level, sum)
    sumRightViewUtil(root.left, level + 1, max_level, sum)
     
 
# A wrapper over sumRightViewUtil()
def sumRightView(root):
    max_level = [0]
    sum =[0]
    sumRightViewUtil(root, 1, max_level, sum)
    print(sum[0])
 
 
# Driver code
root = Node(12)
root.left = Node(10)
root.right = Node(30)
root.right.left = Node(25)
root.right.right = Node(40)
sumRightView(root)




using System;
 
// Class for a node of the tree
class Node
{
    public int Data;
    public Node Left, Right;
 
    public Node(int item)
    {
        Data = item;
        Left = Right = null;
    }
}
 
class BinaryTree
{
    Node Root;
    static int maxLevel = 0;
    static int sum = 0;
 
    // Recursive function to find the sum of nodes
    // of the right view of the given binary tree
    void SumRightViewUtil(Node node, int level)
    {
        // Base Case
        if (node == null)
            return;
 
        // If this is the last node of its level
        if (maxLevel < level)
        {
            sum += node.Data;
            maxLevel = level;
        }
 
        // Recur for right and left subtrees
        SumRightViewUtil(node.Right, level + 1);
        SumRightViewUtil(node.Left, level + 1);
    }
 
    // A wrapper over SumRightViewUtil()
    void SumRightView()
    {
        SumRightViewUtil(Root, 1);
        Console.Write(sum);
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        BinaryTree tree = new BinaryTree();
        tree.Root = new Node(12);
        tree.Root.Left = new Node(10);
        tree.Root.Right = new Node(30);
        tree.Root.Right.Left = new Node(25);
        tree.Root.Right.Right = new Node(40);
 
        tree.SumRightView();
    }
}




<script>
 
    // JavaScript implementation of the approach
     
    // Class for a node of the tree
    class Node {
        constructor(item) {
           this.left = null;
           this.right = null;
           this.data = item;
        }
    }
     
    let root;
    let max_level = 0;
    let sum = 0;
   
    // Recursive function to find the sum of nodes
    // of the right view of the given binary tree
    function sumRightViewUtil(node, level)
    {
        // Base Case
        if (node == null)
            return;
   
        // If this is the last node of its level
        if (max_level < level) {
            sum += node.data;
            max_level = level;
        }
   
        // Recur for left and right subtrees
        sumRightViewUtil(node.right, level + 1);
        sumRightViewUtil(node.left, level + 1);
    }
   
    // A wrapper over sumRightViewUtil()
    function sumRightView()
    {
   
        sumRightViewUtil(root, 1);
        document.write(sum);
    }
     
      root = new Node(12);
    root.left = new Node(10);
    root.right = new Node(30);
    root.right.left = new Node(25);
    root.right.right = new Node(40);
 
    sumRightView();
 
</script>

Output
82



Time Complexity: O(n), where n is the number of nodes in the binary tree.
Auxiliary Space: O(n), where n is the number of nodes in the binary tree.

Iterative Approach(Using Queue):
Follow the below steps  to solve the above problem:
1) Simply traverse the whole binary tree in level Order Traversal with the help of Queue data structure.
2) At each level keep track of the sum and add last node data in sum.
3) Finally print the sum.
Below is the implementation of the above approach:




// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL(KIRTIAGARWAL23121999)
// C++ Program for the above approach
#include<bits/stdc++.h>
using namespace std;
 
struct Node{
    int data;
    Node* left;
    Node* right;
    Node(int data){
        this->data = data;
        this->left = this->right = NULL;
    }
};
 
// A utility function to create a new node
struct Node* newNode(int data){
    return new Node(data);
}
 
void sumRightView(Node* root){
    if(root == NULL) return;
     
    queue<Node*> q;
    q.push(root);
     
    int sum = 0;
    while(!q.empty()){
        int n = q.size();
        for(int i = 0; i<n; i++){
            Node* front_node = q.front();
            q.pop();
            if(i == n-1) sum = sum + front_node->data;
             
            if(front_node->left) q.push(front_node->left);
            if(front_node->right) q.push(front_node->right);
        }
    }
     
    cout<<sum<<endl;
}
 
// driver program to test above function
int main(){
    Node* root = newNode(12);
    root->left = newNode(10);
    root->right = newNode(30);
    root->right->left = newNode(25);
    root->right->right = newNode(40);
     
    sumRightView(root);
    return 0;
}




// Java Program for the above approach
import java.util.*;
 
class Node {
    int data;
    Node left, right;
    Node(int data)
    {
        this.data = data;
        this.left = this.right = null;
    }
}
 
public class Main {
    static void sumRightView(Node root)
    {
        if (root == null)
            return;
        Queue<Node> q = new LinkedList<>();
        q.offer(root);
 
        int sum = 0;
        while (!q.isEmpty()) {
            int n = q.size();
            for (int i = 0; i < n; i++) {
                Node front_node = q.poll();
                if (i == n - 1)
                    sum = sum + front_node.data;
 
                if (front_node.left != null)
                    q.offer(front_node.left);
                if (front_node.right != null)
                    q.offer(front_node.right);
            }
        }
 
        System.out.println(sum);
    }
 
    // driver program to test above function
    public static void main(String[] args)
    {
        Node root = new Node(12);
        root.left = new Node(10);
        root.right = new Node(30);
        root.right.left = new Node(25);
        root.right.right = new Node(40);
 
        sumRightView(root);
    }
}
// This code is contributed by Saroj Mandal




# Python3 Program for the above approach
 
from queue import Queue
 
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
def sumRightView(root):
    if root is None:
        return
     
    q = Queue()
    q.put(root)
     
    sum = 0
    while not q.empty():
        n = q.qsize()
        for i in range(n):
            front_node = q.get()
            if i == n-1:
                sum += front_node.data
                 
            if front_node.left:
                q.put(front_node.left)
            if front_node.right:
                q.put(front_node.right)
     
    print(sum)
 
# driver program to test above function
if __name__ == '__main__':
    root = Node(12)
    root.left = Node(10)
    root.right = Node(30)
    root.right.left = Node(25)
    root.right.right = Node(40)
     
    sumRightView(root)




// C# Program for the above approach
using System;
using System.Collections.Generic;
 
public class Node {
  public int data;
  public Node left;
  public Node right;
  public Node(int data) {
    this.data = data;
    this.left = this.right = null;
  }
}
 
public class MainClass {
  static void sumRightView(Node root) {
    if (root == null)
      return;
    Queue < Node > q = new Queue < Node > ();
    q.Enqueue(root);
    int sum = 0;
    while (q.Count != 0) {
      int n = q.Count;
      for (int i = 0; i < n; i++) {
        Node front_node = q.Dequeue();
        if (i == n - 1)
          sum = sum + front_node.data;
 
        if (front_node.left != null)
          q.Enqueue(front_node.left);
        if (front_node.right != null)
          q.Enqueue(front_node.right);
      }
    }
 
    Console.WriteLine(sum);
  }
 
  // driver program to test above function
  public static void Main() {
    Node root = new Node(12);
    root.left = new Node(10);
    root.right = new Node(30);
    root.right.left = new Node(25);
    root.right.right = new Node(40);
 
    sumRightView(root);
  }
}
 
// Contributed by adityasharmadev01




// JavaScript Program for the above approach
class Node {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}
 
function sumRightView(root) {
  if (!root) return;
 
  const q = [];
  q.push(root);
 
  let sum = 0;
  while (q.length !== 0) {
    const n = q.length;
    for (let i = 0; i < n; i++) {
      const front_node = q.shift();
      if (i === n - 1) sum = sum + front_node.data;
 
      if (front_node.left) q.push(front_node.left);
      if (front_node.right) q.push(front_node.right);
    }
  }
 
  console.log(sum);
}
 
// driver program to test above function
const root = new Node(12);
root.left = new Node(10);
root.right = new Node(30);
root.right.left = new Node(25);
root.right.right = new Node(40);
 
sumRightView(root);

Output
82




Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(N) due to queue data structure.

Another Approach(Using Morris Traversal):

Follow the below steps to solve the above problem:

1) Initialize a sum variable to hold the result.
2) Initialize a pointer curr to the root of the binary tree.
3) While curr is not null, do the following:
    If curr has no right child: Add the value of curr to sum and set curr to its right child.
    Otherwise: Find inorder successor of curr by initializing a pointer next to right child of curr, and    then repeatedly moving left until next has no left child or its left           child is equal to curr.
4) If next has no left child: Add the value of curr to sum, set the left child of next to curr, set curr    to its right child.
    Otherwise: Set the left child of next to null, set curr to its left child. Return sum, which contains    the sum of nodes in right view of binary tree.

Below is the implementation of above approach:




// C++ program to find the sum of nodes
// in right view of binary tree
#include <bits/stdc++.h>
using namespace std;
 
// Structure of the binary tree node
struct Node{
    int data;
    Node* left;
    Node* right;
};
  
// Utility function to create a new Node
Node* newNode(int item){
    Node* temp = new Node();
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
int sumRightView(Node* root){
    int sum = 0;
    Node* curr = root;
    while (curr) {
        // if there is not right child add current node's value to vector
        if (!curr->right) {
            sum += curr->data;
            // move to the right child
            curr = curr->right;
        }
        // If there is a right child
        else {
            // set the next node to the right child
            Node* next = curr->right;
            // traverse the left subtree of the right child until a
            // leaf node or the current node is reached
            while (next->left && next->left != curr)
                next = next->left;
 
            // if the left child of the next node is NULL
            if (!next->left) {
                sum += curr->data;
                next->left = curr;
                curr = curr->right;
            }
            else {
                next->left = NULL;
                curr = curr->left;
            }
        }
    }
    return sum;
}
// Driver code
int main(){
    Node* root = newNode(12);
    root->left = newNode(10);
    root->right = newNode(30);
    root->right->left = newNode(25);
    root->right->right = newNode(40);
  
    cout<<sumRightView(root);
    return 0;
}
// This code is contributed by Yash Agarwal(yashagarwal2852002)




// Java program to find the sum of nodes
// in the right view of a binary tree
import java.util.LinkedList;
import java.util.Queue;
 
// Class representing the structure of a binary tree node
class Node {
    int data;
    Node left, right;
 
    // Constructor to create a new Node
    public Node(int item) {
        data = item;
        left = right = null;
    }
}
 
public class BinaryTree {
     
    // Utility function to find the sum of nodes in the right view
    public static int sumRightView(Node root) {
        int sum = 0;
         
        // Base case: If the tree is empty, return 0
        if (root == null)
            return sum;
 
        // Create a queue for level order traversal
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
 
        // Perform level order traversal
        while (!queue.isEmpty()) {
            int size = queue.size();
 
            // Traverse all nodes at the current level
            for (int i = 0; i < size; i++) {
                Node current = queue.poll();
 
                // If it's the last node at this level, add its value to the sum
                if (i == size - 1)
                    sum += current.data;
 
                // Add the left child to the queue if it exists
                if (current.left != null)
                    queue.add(current.left);
 
                // Add the right child to the queue if it exists
                if (current.right != null)
                    queue.add(current.right);
            }
        }
        return sum;
    }
 
    // Driver code
    public static void main(String[] args) {
        // Creating the binary tree
        Node root = new Node(12);
        root.left = new Node(10);
        root.right = new Node(30);
        root.right.left = new Node(25);
        root.right.right = new Node(40);
 
        // Printing the sum of nodes in the right view
        System.out.println(sumRightView(root));
    }
}




# Python program to find the sum of nodes
# in the right view of a binary tree
class Node:
    def __init__(self, item):
        self.data = item
        self.left = None
        self.right = None
 
# Utility function to create a new Node
def newNode(item):
    temp = Node(item)
    temp.left = temp.right = None
    return temp
 
# Function to find the sum of nodes in the right view
def sumRightView(root):
    sum_result = 0
    curr = root
 
    while curr:
        # If there is no right child, add the current node's value to the sum
        if not curr.right:
            sum_result += curr.data
            # Move to the right child
            curr = curr.right
        else:
            # Set the next node to the right child
            next_node = curr.right
            # Traverse the left subtree of the right child until a
            # leaf node or the current node is reached
            while next_node.left and next_node.left != curr:
                next_node = next_node.left
 
            # If the left child of the next node is NULL
            if not next_node.left:
                sum_result += curr.data
                next_node.left = curr
                curr = curr.right
            else:
                next_node.left = None
                curr = curr.left
 
    return sum_result
 
# Driver code
if __name__ == "__main__":
    root = newNode(12)
    root.left = newNode(10)
    root.right = newNode(30)
    root.right.left = newNode(25)
    root.right.right = newNode(40)
 
    result = sumRightView(root)
    print(result)




using System;
 
// Structure of the binary tree node
public class Node
{
    public int data;
    public Node left, right;
 
    // Constructor to create a new Node
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
public class BinaryTree
{
    // Function to find the sum of nodes in the right view of the binary tree
    public static int SumRightView(Node root)
    {
        int sum = 0;
        Node curr = root;
        while (curr != null)
        {
            // if there is no right child, add current node's value to the sum
            if (curr.right == null)
            {
                sum += curr.data;
                // move to the right child
                curr = curr.right;
            }
            // If there is a right child
            else
            {
                // set the next node to the right child
                Node next = curr.right;
                // traverse the left subtree of the right child until a
                // leaf node or the current node is reached
                while (next.left != null && next.left != curr)
                    next = next.left;
 
                // if the left child of the next node is null
                if (next.left == null)
                {
                    sum += curr.data;
                    next.left = curr;
                    curr = curr.right;
                }
                else
                {
                    next.left = null;
                    curr = curr.left;
                }
            }
        }
        return sum;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        Node root = new Node(12);
        root.left = new Node(10);
        root.right = new Node(30);
        root.right.left = new Node(25);
        root.right.right = new Node(40);
 
        Console.WriteLine(SumRightView(root));
    }
}




// Structure of the binary tree node
class Node {
    constructor(data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
 
// Utility function to create a new Node
function newNode(item) {
    const temp = new Node();
    temp.data = item;
    temp.left = temp.right = null;
    return temp;
}
 
// Function to find the sum of nodes in the right view of a binary tree
function sumRightView(root) {
    let sum = 0;
    let curr = root;
 
    while (curr) {
        // If there is no right child, add the current node's value to the sum
        if (!curr.right) {
            sum += curr.data;
            // Move to the right child
            curr = curr.right;
        }
        // If there is a right child
        else {
            // Set the next node to the right child
            let next = curr.right;
             
            // Traverse the left subtree of the right child until a
            // leaf node or the current node is reached
            while (next.left && next.left !== curr)
                next = next.left;
 
            // If the left child of the next node is NULL
            if (!next.left) {
                sum += curr.data;
                next.left = curr;
                curr = curr.right;
            } else {
                next.left = null;
                curr = curr.left;
            }
        }
    }
 
    return sum;
}
 
// Driver code
const root = newNode(12);
root.left = newNode(10);
root.right = newNode(30);
root.right.left = newNode(25);
root.right.right = newNode(40);
 
console.log(sumRightView(root));
// This Code is contributed by Yash Agarwal(yashagarwal2852002)

Output
82



Time Complexity: O(n), where n is the number of nodes in given binary tree.
Auxiliary Space: O(1)


Article Tags :