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 tocorrectBinaryTree
)int toNode
(not available tocorrectBinaryTree
)
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
.
Example 1:
Input: root = [1,2,3], fromNode = 2, toNode = 3 Output: [1,null,3] Explanation: The node with value 2 is invalid, so remove it.
Example 2:
Input: root = [8,3,1,7,null,9,4,2,null,null,null,5,6], fromNode = 7, toNode = 4 Output: [8,3,1,null,null,9,4,null,null,5,6] Explanation: The node with value 7 is invalid, so remove it and the node underneath it, node 2.
树中有个节点指针错了,其右指针指向了同一个level的另外一个节点。
同一层的问题,首先想到的是BSF(queue)。
那问题就变成了
1)BSF搜索树,然后在queue里去找同一层被错误节点7 指错的节点4.
2)找到错误节点7以后,就得更新其父亲节点3的指针,把3的左孩子7拿掉。
1) 个问题中, 在queue里去找被错误节点7指向的节点4. queue里好像没有提供find函数。
于是用unord_ered_set 去存储同一层的node,当同一层的node都被push进queue并且没有找到相应的node,就clear unorder_set.
2)更新父亲节点的孩子指针问题,需要在push queue的head 节点的左右子孩子进queue之前去找左右孩子是不是犯错误的node,如果是就直接把这个孩子踢掉。
代码如下。
/**
* 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) {
if(root == NULL)
return root;
TreeNode* head = root;
queue<TreeNode*> myqueue;
unordered_set<TreeNode*> SameLevelNodes;
myqueue.push(root);
while(!myqueue.empty()) {
int size = myqueue.size();
for(int i =0;i < size;i++) {
root = myqueue.front();
myqueue.pop();
TreeNode* right, *left;
if(root->right != NULL) {
right = root->right;
myqueue.push(right);
SameLevelNodes.insert(right);
if (SameLevelNodes.find(right->right) != SameLevelNodes.end() ) {
root->right = NULL;
return head;
}
}
if(root->left != NULL) {
left = root->left;
myqueue.push(left);
SameLevelNodes.insert(left);
if(SameLevelNodes.find(left->right) != SameLevelNodes.end() )
{
root->left = NULL;
return head;
}
}
}
SameLevelNodes.clear();
}
return head;
}
};