forked from Raju1822/HacktoberFest_2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Boundary Nodes Sum.txt
82 lines (71 loc) · 1.99 KB
/
Boundary Nodes Sum.txt
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
82
static void LeftBoundary(Node root)
{
if (root != null)
{
if (root.left != null)
{
sum_of_boundary_nodes += root.data;
LeftBoundary(root.left);
}
else if (root.right != null)
{
sum_of_boundary_nodes += root.data;
LeftBoundary(root.right);
}
}
}
// Function to sum up all the right boundary nodes
// except the leaf nodes
static void RightBoundary(Node root)
{
if (root != null)
{
if (root.right != null)
{
RightBoundary(root.right);
sum_of_boundary_nodes += root.data;
}
else if (root.left != null)
{
RightBoundary(root.left);
sum_of_boundary_nodes += root.data;
}
}
}
// Function to sum up all the leaf nodes
// of a binary tree
static void Leaves(Node root)
{
if (root != null)
{
Leaves(root.left);
// Sum it up if it is a leaf node
if ((root.left == null) && (root.right == null))
sum_of_boundary_nodes += root.data;
Leaves(root.right);
}
}
// Function to return the sum of all the
// boundary nodes of the given binary tree
static int sumOfBoundaryNodes( Node root)
{
if (root != null)
{
// Root node is also a boundary node
sum_of_boundary_nodes = root.data;
// Sum up all the left nodes
// in TOP DOWN manner
LeftBoundary(root.left);
// Sum up all the
// leaf nodes
Leaves(root.left);
Leaves(root.right);
// Sum up all the right nodes
// in BOTTOM UP manner
RightBoundary(root.right);
// Return the sum of
// all the boundary nodes
return sum_of_boundary_nodes;
}
return 0;
}