-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2458.cpp
More file actions
54 lines (50 loc) · 1.63 KB
/
2458.cpp
File metadata and controls
54 lines (50 loc) · 1.63 KB
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> heights;
vector<int> depths;
unordered_map<int, vector<int>> d2hs;
int depthDfs(TreeNode* node, int depth) {
if (node == nullptr) return -1;
int left = depthDfs(node->left, depth + 1);
int right = depthDfs(node->right, depth + 1);
heights[node->val] = max(left, right) + 1;
depths[node->val] = depth;
d2hs[depth].push_back(max(left, right) + 1);
return max(left, right) + 1;
}
vector<int> treeQueries(TreeNode* root, vector<int>& queries) {
heights.resize(100001, -1);
depths.resize(100001, -1);
depthDfs(root, 0);
for (auto& [d, hs] : d2hs) {
sort(hs.begin(), hs.end(), greater<int>());
}
int m = queries.size();
vector<int> res(m, 0);
for (int i = 0; i < m; ++i) {
int depth = depths[queries[i]];
int height = heights[queries[i]];
if (d2hs[depth].size() == 1) {
res[i] = depth - 1;
}
else if (d2hs[depth][0] == height) {
res[i] = d2hs[depth][1] + depth;
}
else {
res[i] = d2hs[depth][0] + depth;
}
}
return res;
}
};