Skip to content

Commit 6a14b83

Browse files
authored
Create 2458. Height of Binary Tree After Subtree Removal Queries (#618)
2 parents 3515b76 + 4c4e357 commit 6a14b83

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Solution {
2+
public:
3+
vector< pair<int, int> > h = vector<pair<int, int>>(100001, {0, 0});
4+
pair<int, int> solve(TreeNode* root, int level){
5+
if(root == nullptr) return {0, 0};
6+
if(root->left == nullptr && root->right == nullptr){
7+
return h[root->val] = {1, level};
8+
}
9+
//traversing the tree and updating the h vector
10+
solve(root->left, level + 1);
11+
solve(root->right, level + 1);
12+
13+
h[root->val] = {max(
14+
root->right != nullptr ? h[root->right->val].first : 0,
15+
root->left != nullptr ? h[root->left->val].first : 0
16+
) + 1, level};
17+
return h[root->val];
18+
}
19+
vector<int> treeQueries(TreeNode* root, vector<int>& queries) {
20+
solve(root, 0);
21+
vector<int> ans;
22+
vector<int> v[100000];
23+
int longestPath = 0;
24+
for(auto x : h){ // filling the v vector while calculating longestPath
25+
if(x.second == 0) continue;
26+
longestPath = max(longestPath, x.first);
27+
v[x.second].push_back(x.first);
28+
}
29+
30+
// Sort to get the longest && the second longest path of each level
31+
for(auto &x : v) sort(x.begin(), x.end(), greater<int>());
32+
33+
for(auto &q : queries){
34+
int node = q;
35+
int level = h[node].second;
36+
if(h[node].first == v[level][0] && v[level].size() >= 2){
37+
q = longestPath - v[level][0] + v[level][1];
38+
continue;
39+
}else if(h[node].first == v[level][0]){
40+
q = longestPath - v[level][0];
41+
continue;
42+
}
43+
q = longestPath;
44+
}
45+
46+
return queries;
47+
}
48+
};

0 commit comments

Comments
 (0)