forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcorrect-a-binary-tree.cpp
More file actions
30 lines (29 loc) · 882 Bytes
/
correct-a-binary-tree.cpp
File metadata and controls
30 lines (29 loc) · 882 Bytes
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
// Time: O(n)
// Space: O(w)
class Solution {
public:
TreeNode* correctBinaryTree(TreeNode* root) {
unordered_map<TreeNode*, TreeNode*> q = {{root, nullptr}};
while (!empty(q)) {
unordered_map<TreeNode*, TreeNode*> new_q;
for (const auto& [node, parent] : q) {
if (q.count(node->right)) {
if (parent->left == node) {
parent->left = nullptr;
} else {
parent->right = nullptr;
}
return root;
}
if (node->left) {
new_q[node->left] = node;
}
if (node->right) {
new_q[node->right] = node;
}
}
q = move(new_q);
}
return nullptr;
}
};