Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 584729a

Browse files
Merge pull request #111 from sarthakdelori/sarthak-sum-of-nodes
create-sum-of-all-nodes.cpp
2 parents 587aa51 + 4183564 commit 584729a

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

‎18-Binary Tree/sum-of-all-nodes.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /