-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sum of leaf nodes in BST.cpp
111 lines (97 loc) · 2.16 KB
/
Sum of leaf nodes in BST.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
struct Node
{
int data;
struct Node *left;
struct Node *right;
Node(int x){
data = x;
left = NULL;
right = NULL;
}
};
Node *insert(Node *r,int num);
void preOrderDisplay(Node *r);
void inOrderDisplay(Node *r);
void postOrderDisplay(Node *r);
int search(Node *r, int num);
class Solution
{
public:
/*You are required to complete below method */
int sum=0;
int sumOfLeafNodes(Node *root ){
if(root==NULL)
{
return 0;
}
sumOfLeafNodes(root->left);
sumOfLeafNodes(root->right);
if(root->left==NULL && root->right==NULL)
{
sum+=root->data;
}
return sum;
}
};
int main(void) {
int t,n,data;
scanf("%d",&t);
while(t--){
Node *root=NULL;
scanf("%d",&n);
//printf("n=%d\n",n);
while(n--){
scanf("%d",&data);
//printf("data=%d\n",data);
root=insert(root,data);
}
//inOrderDisplay(root);
Solution obj;
printf("%d\n",obj.sumOfLeafNodes(root));
}
return 0;
}
Node *insert(Node *r,int num){
if(r==NULL){
r = new Node(num);
}else{
if(num<r->data){
r->left=insert(r->left,num);
}else{
r->right=insert(r->right,num);
}
}
return r;
}
void preOrderDisplay(Node *r){
if(r!=NULL){
printf("%d ",r->data);
preOrderDisplay(r->left);
preOrderDisplay(r->right);
}
}
void inOrderDisplay(Node *r){
if(r!=NULL){
inOrderDisplay(r->left);
printf("%d ",r->data);
inOrderDisplay(r->right);
}
}
void postOrderDisplay(Node *r){
if(r!=NULL){
postOrderDisplay(r->left);
postOrderDisplay(r->right);
printf("%d ",r->data);
}
}
int search(Node *r,int num){
if(r==NULL)return 0;
else if(r->data==num)return 0;
else if(r->data > num)
search(r->left,num);
else
search(r->right,num);
}