Find a Corresponding Node of a Binary Tree in a Clone

medium tree dfs

Problem

You are given two binary trees: original and a cloned copy that is structurally identical to it. You also get a reference to one node, target, that belongs to the original tree. Return the node in the cloned tree that sits at the very same position as target. You may assume the values are not necessarily distinct, so you must rely on position rather than value.

Inputoriginal = "7, 4, 3, _, _, 6, 19", target = 3
Output3
Trees use level-order notation; "_" means a missing child. The target node has value 3, so we return the node at that same spot in the clone (value 3).

def get_target_copy(original, cloned, target):
    if original is None:
        return None
    if original is target:
        return cloned
    left = get_target_copy(original.left, cloned.left, target)
    if left is not None:
        return left
    return get_target_copy(original.right, cloned.right, target)
function getTargetCopy(original, cloned, target) {
  if (original === null) return null;
  if (original === target) return cloned;
  const left = getTargetCopy(original.left, cloned.left, target);
  if (left !== null) return left;
  return getTargetCopy(original.right, cloned.right, target);
}
class Solution {
    public TreeNode getTargetCopy(TreeNode original, TreeNode cloned, TreeNode target) {
        if (original == null) return null;
        if (original == target) return cloned;
        TreeNode left = getTargetCopy(original.left, cloned.left, target);
        if (left != null) return left;
        return getTargetCopy(original.right, cloned.right, target);
    }
}
TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) {
    if (original == nullptr) return nullptr;
    if (original == target) return cloned;
    TreeNode* left = getTargetCopy(original->left, cloned->left, target);
    if (left != nullptr) return left;
    return getTargetCopy(original->right, cloned->right, target);
}
Time: O(n) Space: O(h) recursion