Similar Problems

Similar Problems not available

Find A Corresponding Node Of A Binary Tree In A Clone Of That Tree - Leetcode Solution

Companies:

LeetCode:  Find A Corresponding Node Of A Binary Tree In A Clone Of That Tree Leetcode Solution

Difficulty: Easy

Topics: binary-tree tree depth-first-search breadth-first-search  

Problem statement: 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.

Solution: To solve this problem, we can traverse both the original and cloned trees in parallel and at each step, compare if the current node in the original tree is the same as the target node. If it is, then the node we are currently at in the cloned tree is the corresponding node.

Algorithm:

  1. Start traversing the original tree using breadth-first-search (BFS) algorithm.

  2. At each step, compare if the current node in the original tree is the same as the target node.

  3. If it is the same, then return the current node in the cloned tree.

  4. Otherwise, add the left and right children of the current node to the BFS queue if they exist.

  5. Repeat steps 2-4 until we have found the target node or the BFS queue is empty.

Here is the implementation of the algorithm in Python:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
        
def getTargetCopy(original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
    queue = [(original, cloned)]

    while queue:
        orig_node, cloned_node = queue.pop(0)

        if orig_node == target:
            return cloned_node
        
        if orig_node.left:
            queue.append((orig_node.left, cloned_node.left))

        if orig_node.right:
            queue.append((orig_node.right, cloned_node.right))

In this implementation, we start by creating a queue containing a tuple with the original node and its corresponding cloned node.

We then use a while loop to pop the first element from the queue and compare if the current node in the original tree is the same as the target node.

If it is, then we return the current node in the cloned tree.

Otherwise, we add the left and right children of the current node to the queue if they exist.

We continue this process until we have found the target node or the BFS queue is empty.

Time Complexity: O(n), where n is the number of nodes in the binary tree. We need to traverse all nodes in the tree.

Space Complexity: O(n), where n is the number of nodes in the binary tree. In the worst-case scenario, the BFS queue can contain all nodes in the tree.

Find A Corresponding Node Of A Binary Tree In A Clone Of That Tree Solution Code

1