|
| 1 | +/****************************************************************************** |
| 2 | + |
| 3 | +program to find sum of all the nodes in a tree. |
| 4 | +the program is using level order traversal or BFS. |
| 5 | + |
| 6 | +*******************************************************************************/ |
| 7 | + |
| 8 | +#include <iostream> |
| 9 | +#include <bits/stdc++.h> |
| 10 | +using namespace std; |
| 11 | + |
| 12 | +class Node { |
| 13 | + public: |
| 14 | + int data; |
| 15 | + struct Node *left, *right; |
| 16 | + Node(int x){ |
| 17 | + data = x; |
| 18 | + left = right = NULL; |
| 19 | + } |
| 20 | +}; |
| 21 | + |
| 22 | +int main() |
| 23 | +{ |
| 24 | + Node* root = new Node(1); |
| 25 | + root->left = new Node(2); |
| 26 | + root->right = new Node(3); |
| 27 | + root->left->left = new Node(4); |
| 28 | + root->left->right = new Node(5); |
| 29 | + root->right->left = new Node(6); |
| 30 | + root->right->right = new Node(7); |
| 31 | + |
| 32 | + int sum = 0; |
| 33 | + |
| 34 | + queue<Node*> q; |
| 35 | + q.push(root); |
| 36 | + |
| 37 | + while (!q.empty()) { |
| 38 | + Node* temp = q.front(); |
| 39 | + q.pop(); |
| 40 | + |
| 41 | + sum += temp->data; |
| 42 | + |
| 43 | + if (temp->left) { |
| 44 | + q.push(temp->left); |
| 45 | + } |
| 46 | + if (temp->right) { |
| 47 | + q.push(temp->right); |
| 48 | + } |
| 49 | + } |
| 50 | + cout<<sum<<endl; |
| 51 | + return 0; |
| 52 | +} |
| 53 | + |
0 commit comments