-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDistribute candies in a binary tree.cpp
61 lines (53 loc) · 1.25 KB
/
Distribute candies in a binary tree.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
/*---------TWO APPROACHES----------*/
//METHOD - 1
// Time complexity - O(N)
// Space complexity- O(height of tree)
class Solution
{
public:
int help(Node* root,int& ans)
{
//base case
if(!root)
return 0;
//recursive callls
//and small calculation
int left=help(root->left,ans);
int right=help(root->right,ans);
ans+=abs(left)+abs(right);
return root->key+left+right-1;
}
int distributeCandy(Node* root)
{
int ans=0;
int call=help(root,ans);
return ans;
}
};
//METHOD - 2
// Time complexity - O(N)
// Space complexity- O(height of tree)
typedef pair<int,int> pi;
class Solution
{
public:
pi help(Node* root)
{
//base case
if(!root)
return {0,0};
//recursive callls
//and small calculation
pi left=help(root->left);
pi right=help(root->right);
pi temp;
temp.first=abs(left.second)+abs(right.second)+left.first+right.first;
temp.second=root->key+left.second+right.second-1;
return temp;
}
int distributeCandy(Node* root)
{
pi ans=help(root);
return ans.first;
}
};