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

Given two binary trees original and cloned and given a reference to a node target in the original tree.

The cloned tree is a copy of the original tree.

Return a reference to the same node in the cloned tree.

Note that:

  • You are not allowed to change any of the two trees or the target node
  • The answer must be a reference to a node in the cloned tree

Input & Output

Example 1 — Basic Tree
$ Input: original = [7,4,3,null,null,6,19], cloned = [7,4,3,null,null,6,19], target = 3
Output: 3
💡 Note: The target node has value 3. We find the corresponding node in the cloned tree and return it.
Example 2 — Single Node
$ Input: original = [7], cloned = [7], target = 7
Output: 7
💡 Note: Both trees have only one node. The target is the root, so we return the cloned root.
Example 3 — Duplicate Values
$ Input: original = [8,null,6,null,5,null,4,null,3,null,2,null,1], cloned = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4
Output: 4
💡 Note: Even with duplicate values possible, we find the exact corresponding node position in the cloned tree.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • The values of the nodes of the tree are unique
  • target node is a node from the original tree and is not null

Visualization

Tap to expand
Find Corresponding Node in Cloned Tree INPUT Original Tree 7 4 3 target 6 19 Cloned Tree 7 4 3 find this 6 19 original = [7,4,3,null,null,6,19] cloned = [7,4,3,null,null,6,19] target = 3 Both trees are identical. Find node with value 3 in the cloned tree. ALGORITHM STEPS 1 Start Simultaneous DFS Traverse both trees together 2 Check Current Node Is original node == target? 3 If Match Found Return cloned node reference 4 Recurse Children Search left and right subtrees Traversal Path Original: Cloned: 7 4 3 7 4 3 Match! Return cloned.3 FINAL RESULT Cloned Tree with Found Node 7 4 3 6 19 Found Node Output: 3 OK - Reference Found Same position in clone Key Insight: By traversing both trees simultaneously with identical steps, when we find the target in the original tree, the current node in the cloned tree is at the exact same position. This avoids value-based searching and works even when there are duplicate values in the tree. TutorialsPoint - Find a Corresponding Node of a Binary Tree in a Clone of That Tree | Simultaneous DFS Traversal
Asked in
Facebook 15 Amazon 12 Google 8
89.7K Views
Medium Frequency
~10 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen