Skip to main content
Back to problems
#1660
Medium Algorithms

Correct a binary tree

Hash Table Tree Depth-First Search Breadth-First Search Binary Tree
74.3% acceptance
Mar 31, 2026
277
47
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.

Solution

C++
Time O(1)
Space O(1)
LeetCode
solution.cpp
/**
 * 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:
  unordered_set<TreeNode*> visited;
  
  TreeNode* correctBinaryTree(TreeNode* root) {
    if (!root) return nullptr;
    if (root->right && visited.count(root->right)) return nullptr;
    visited.insert(root);
    root->right = correctBinaryTree(root->right);
    root->left = correctBinaryTree(root->left);
    return root;
  }
};