Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree in C++
In this tutorial, we will be discussing a program to convert a binary tree such that every node stores the sum of all nodes in its right subtree.
For this, we will be provided with a binary tree. Our task is to return another tree where every node must be equal to the sum of the node and its right subtree.
Example
#include <bits/stdc++.h>
using namespace std;
//node structure of tree
struct Node {
int data;
Node *left, *right;
};
//creation of a new node
struct Node* createNode(int item){
Node* temp = new Node;
temp->data = item;
temp->left = NULL;
temp->right = NULL;
return temp;
}
//creating the new binary tree
int rightsum_tree(Node* root){
if (!root)
return 0;
if (root->left == NULL && root->right == NULL)
return root->data;
//changing the values of left/right subtree
int rightsum = rightsum_tree(root->right);
int leftsum = rightsum_tree(root->left);
//adding the sum of right subtree
root->data += rightsum;
return root->data + leftsum;
}
//traversing tree in inorder pattern
void inorder(struct Node* node){
if (node == NULL)
return;
inorder(node->left);
cout << node->data << " ";
inorder(node->right);
}
int main(){
struct Node* root = NULL;
root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->right = createNode(6);
rightsum_tree(root);
cout << "Updated Binary Tree :\n";
inorder(root);
return 0;
}
Output
Updated Binary Tree : 4 7 5 10 9 6
Advertisements