[LeetCode] Correct a Binary Tree

1660. Correct a Binary Tree

You have a binary tree with a small defect. There is exactly one invalid node where its right child incorrectly points to another node at the same depth but to the invalid node’s right.

Given the root of the binary tree with this defect, root, return the root of the binary tree after removing this invalid node and every node underneath it (minus the node it incorrectly points to).

Custom testing:

The test input is read as 3 lines:

  • TreeNode root
  • int fromNode (not available to correctBinaryTree)
  • int toNode (not available to correctBinaryTree)

After the binary tree rooted at root is parsed, the TreeNode with value of fromNode will have its right child pointer pointing to the TreeNode with a value of toNode. Then, root is passed to correctBinaryTree.

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
/**
* 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:
TreeNode* correctBinaryTree(TreeNode* root) {
unordered_map<TreeNode*, int> level;
unordered_map<TreeNode*, TreeNode*> par;
queue<TreeNode*> q;
q.push(root);
par[root] = nullptr;
level[root] = 0;
while(!q.empty()) {
int sz = q.size();
while(sz--) {
TreeNode* now = q.front(); q.pop();
if(now->left) {
if(level.count(now->left)) {
TreeNode* p = par[now];
if(p->left == now) p->left = nullptr;
if(p->right == now) p->right = nullptr;
return root;
}
level[now->left] = level[now] + 1;
par[now->left] = now;
q.push(now->left);
}
if(now->right) {
if(level.count(now->right)) {
TreeNode* p = par[now];
if(p->left == now) p->left = nullptr;
if(p->right == now) p->right = nullptr;
return root;
}
level[now->right] = level[now] + 1;
par[now->right] = now;
q.push(now->right);
}
}

}
return root;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/08/PS/LeetCode/correct-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.