forked from rathoresrikant/HacktoberFestContribute
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SumofLeafNodes.cpp
55 lines (47 loc) · 1.11 KB
/
SumofLeafNodes.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// CPP program to find sum of
// all leaf nodes of binary tree
#include<bits/stdc++.h>
using namespace std;
// struct binary tree node
struct Node{
int data;
Node *left, *right;
};
// return new node
Node *newNode(int data){
Node *temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// utility function which calculates
// sum of all leaf nodes
void leafSum(Node *root, int *sum){
if (!root)
return;
// add root data to sum if
// root is a leaf node
if (!root->left && !root->right)
*sum += root->data;
// propagate recursively in left
// and right subtree
leafSum(root->left, sum);
leafSum(root->right, sum);
}
// driver program
int main(){
//contruct binary tree
Node *root = newNode(1);
root->left = newNode(2);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right = newNode(3);
root->right->right = newNode(7);
root->right->left = newNode(6);
root->right->left->right = newNode(8);
// variable to store sum of leaf nodes
int sum = 0;
leafSum(root, &sum);
cout << sum << endl;
return 0;
}