-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsum-of-right-leaves.cpp
81 lines (68 loc) · 1.68 KB
/
sum-of-right-leaves.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// The sum of right leaves algorithm uses a queue to navigate through a binary tree
// Worst Case Time Complexity: O(n)
// Average Time Complexity: O(n)
#include <iostream>
#include <queue>
using namespace std;
// Node structure for tree
struct Node {
int val;
Node *left;
Node *right;
Node(int val) {
this->val = val;
left = nullptr;
right = nullptr;
}
};
int sumRightLeaves(Node* root) {
queue<Node*> q;
int rightSum = 0;
// Checking if the root is nullptr push to queue if it exists
if(root)
{
q.push(root);
}
while(!q.empty())
{
// Check if there exists a right node
if(q.front()->right)
{
// Check if this is a leaf node
if(q.front()->right->right == nullptr && q.front()->right->left == nullptr)
{
rightSum += q.front()->right->val;
}
else
{
q.push(q.front()->right);
}
}
if(q.front()->left) // Check down left side of tree
{
q.push(q.front()->left);
}
q.pop();
}
return rightSum;
}
int main()
{
Node* root = new Node(3);
root->left = new Node(5);
root->right = new Node(7);
root->left->left = new Node(8);
root->left->right = new Node(10);
root->right->right = new Node(13);
// 3
// / \
// 5 7
// / \ \
// 8 10 13
//
// Sample Output
// Sum of the right leaves: 23
// Outputting sum of right leaves
cout << "Sum of right leaves: " << sumRightLeaves(root);
return 0;
}