Given two binary trees original and cloned, and given a reference to a node target in the original tree, the task is to find the corresponding node in the cloned tree.
Both trees are identical in structure and the nodes contain the same values, only their memory locations are different. The problem guarantees that the target node is a node in the original tree and we need to return the corresponding node in the cloned tree.
target
node, not just the value.The approach involves traversing both the original and cloned trees simultaneously. When the target node is found in the original tree, the node at the same position in the cloned tree will be our result.
We’ll use a simple DFS (Depth First Search) or BFS (Breadth First Search) to traverse both trees simultaneously.
Here’s a Python implementation using DFS recursively:
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
# Base case: if the original tree node is None, return None
if original is None:
return None
# If the original node is the target node, return the corresponding node in the cloned tree
if original == target:
return cloned
# Search in the left subtree
left_result = self.getTargetCopy(original.left, cloned.left, target)
if left_result is not None:
return left_result
# If the target is not found in the left subtree, search in the right subtree
return self.getTargetCopy(original.right, cloned.right, target)
Time Complexity: (O(N)), where (N) is the number of nodes in the original (and cloned) tree. This is because in the worst case, we might need to visit all nodes to find the target.
Space Complexity: (O(H)), where (H) is the height of the tree, accounting for the recursion stack. In the worst case (an unbalanced tree), (H) can be (N), making the space complexity (O(N)). For a balanced tree, it would be (O(\log N)).
This solution efficiently finds the corresponding node by recursively traversing both trees in sync until the target node is found.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?