Skip to content

1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree 👎

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned,
                          TreeNode* target) {
    TreeNode* ans = nullptr;
    dfs(original, cloned, target, ans);
    return ans;
  }

 private:
  void dfs(TreeNode* original, TreeNode* cloned, TreeNode* target,
           TreeNode*& ans) {
    if (ans != nullptr)
      return;
    if (original == nullptr)
      return;
    if (original == target) {
      ans = cloned;
      return;
    }
    dfs(original->left, cloned->left, target, ans);
    dfs(original->right, cloned->right, target, ans);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned,
                                      final TreeNode target) {
    dfs(original, cloned, target);
    return ans;
  }

  private TreeNode ans = null;

  private void dfs(TreeNode original, TreeNode cloned, TreeNode target) {
    if (ans != null)
      return;
    if (original == null)
      return;
    if (original == target) {
      ans = cloned;
      return;
    }
    dfs(original.left, cloned.left, target);
    dfs(original.right, cloned.right, target);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
  def getTargetCopy(
      self,
      original: TreeNode,
      cloned: TreeNode,
      target: TreeNode,
  ) -> TreeNode:
    ans = None

    def dfs(original: TreeNode, cloned: TreeNode) -> None:
      nonlocal ans
      if ans:
        return
      if not original:
        return
      if original == target:
        ans = cloned
        return

      dfs(original.left, cloned.left)
      dfs(original.right, cloned.right)

    dfs(original, cloned)
    return ans