-
Notifications
You must be signed in to change notification settings - Fork 2
/
Bheem Wants Ladoos.cpp
54 lines (46 loc) · 1.3 KB
/
Bheem Wants Ladoos.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
class Solution{
private:
void add_subtree(Node* n, int dist, int* sum)
{
if( !n || dist<0 ) return;
*sum += n->data;
add_subtree(n->left, dist-1, sum);
add_subtree(n->right, dist-1, sum);
}
int traverse(Node* n, int target, int k, int* sum)
{
if(!n) return -1;
if(n->data==target)
{
add_subtree(n, k, sum);
// adding all nodes within range in the sub tree below
return k-1;
}
int dist = traverse(n->left, target, k, sum);
if(dist>-1)
// dist>-1 indicates target was found in left subtree
{
*sum += n->data;
add_subtree(n->right, dist-1, sum);
// adding values from right sub tree
return dist-1;
}
dist = traverse(n->right, target, k, sum);
if(dist>-1)
// dist>-1 indicates target was found in right subtree
{
*sum += n->data;
add_subtree(n->left, dist-1, sum);
// adding values from left sub tree
return dist-1;
}
return -1;
}
public:
int ladoos(Node* root, int home, int k)
{
int sum = 0;
traverse(root, home, k, &sum);
return sum;
}
};