[InterviewBit] Covered / Uncovered Nodes

Covered / Uncovered Nodes

  • Time :
  • Space :
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void dfs(TreeNode* A, vector<vector<int>>& unc, int d, long long& sum) {
if(!A) return;
if(unc.size() == d) unc.emplace_back();
if(unc[d].size() == 2) unc[d].pop_back();
unc[d].push_back(A->val);
sum += A->val;
dfs(A->left, unc, d + 1, sum);
dfs(A->right, unc, d + 1, sum);
}
long Solution::coveredNodes(TreeNode* A) {
vector<vector<int>> unc;
long long sum = 0;
dfs(A,unc,0,sum);
long long u = 0, c = sum;
for(auto vec : unc) {
for(auto v : vec) {
u += v;
c -= v;
}
}
return abs(u-c);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/15/PS/interviewbit/covered-uncovered-nodes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.