We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find a Corresponding Node of a Binary Tree in a Clone of That Tree

Difficulty: Easy


Problem Description

Given two binary trees original and cloned and a reference to a node target in the original tree, return a reference to the same node in the cloned tree. The cloned tree is a copy of the original tree. You are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.


Key Insights

  • The original and cloned trees are structurally identical and contain the same values.
  • A Depth-First Search (DFS) or Breadth-First Search (BFS) can be employed to find the corresponding node in the cloned tree.
  • Since the values of the nodes are unique, we can directly compare the values of the nodes.

Space and Time Complexity

Time Complexity: O(N), where N is the number of nodes in the tree, as we may need to visit every node. Space Complexity: O(H), where H is the height of the tree, due to the recursive call stack in DFS or the queue in BFS.


Solution

To find the corresponding node in the cloned tree, we can perform a traversal of the cloned tree while simultaneously checking if we match the target node from the original tree. We can utilize either DFS or BFS for this purpose. The main idea is to traverse the cloned tree and compare each node with the target node. When a match is found, we return that node.


Code Solutions

def getTargetCopy(original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
    if not cloned:
        return None
    
    # If the current node in the cloned tree matches the target, return it
    if cloned.val == target.val:
        return cloned
    
    # Search in the left subtree
    left_result = getTargetCopy(original, cloned.left, target)
    if left_result:
        return left_result
    
    # Search in the right subtree
    return getTargetCopy(original, cloned.right, target)
← Back to All Questions