« Sum of Nodes in a tree
Find sum of nodes
Given a generic tree, find and return the sum of all nodes present in the given tree.
Input format :
The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space.
Output Format :
The first and only line of output prints the sum of all nodes of the given generic tree.
Constraints:
Time Limit: 1 sec
Sample Input 1:
10 3 20 30 40 2 40 50 0 0 0 0 Sample Output 1:
190
1#include <iostream>2#include <vector>3#include <queue>4using namespace std;56template <typename T>7class TreeNode {8 public:9 T data;10 vector<TreeNode<T>*> children;1112 TreeNode(T data) { this->data = data; }1314 ~TreeNode() {15 for (int i = 0; i < children.size(); i++) {16 delete children[i];17 }18 }19};2021int sumOfNodes(TreeNode<int>* root) {22 int ans = root->data;23 for(int i=0; i<root->children.size(); i++){24 ans += sumOfNodes(root->children[i]);25 }26 return ans;27}2829TreeNode<int>* takeInputLevelWise() {30 int rootData;31 cin >> rootData;32 TreeNode<int>* root = new TreeNode<int>(rootData);3334 queue<TreeNode<int>*> pendingNodes;3536 pendingNodes.push(root);37 while (pendingNodes.size() != 0) {38 TreeNode<int>* front = pendingNodes.front();39 pendingNodes.pop();40 int numChild;41 cin >> numChild;42 for (int i = 0; i < numChild; i++) {43 int childData;44 cin >> childData;45 TreeNode<int>* child = new TreeNode<int>(childData);46 front->children.push_back(child);47 pendingNodes.push(child);48 }49 }5051 return root;52}5354int main() {55 TreeNode<int>* root = takeInputLevelWise();56 cout << sumOfNodes(root);57}