Problem 1379

Abstract / Summary

Given two identical binary trees, find the node in the second tree that corresponds to a given node in the first tree.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1379.py

class Solution:
    def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
        # maybe I could traverse only "cloned" and ignore "original"
        if not original:
            return None

        if original.val == target.val: # same as cloned.val == target.val
            return cloned

        return self.getTargetCopy(original.left,  cloned.left,  target) or \
               self.getTargetCopy(original.right, cloned.right, target)
11 lines | 493 bytes | submitted November 25, 2023 | GitHub   25% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 86% (300k+ submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Breadth First Search
  • Depth First Search
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method that, given the root of an original binary tree, the root of its exact clone, and a reference to a target node in the original tree, returns the node in the cloned tree that occupies the same position. The algorithm walks the two trees in parallel, comparing node values only when the original node matches the target, and stops as soon as the corresponding cloned node is located.

Key Steps

The recursion begins with a guard that checks whether the current node in the original tree exists. If the original subtree is empty, the function returns None, indicating that the target cannot be found in this branch.

if not original:
    return None

When the current original node holds the same value as the target node, the function immediately returns the cloned node that resides at the same structural location. Because the clone is a perfect copy, matching values guarantee that the cloned node is the correct counterpart.

if original.val == target.val:   # same as cloned.val == target.val
    return cloned

If the target has not been found at the current position, the method proceeds to explore the left subtree followed by the right subtree. The recursive calls are combined with the logical or operator, which yields the first non-None result encountered, thereby short-circuiting further exploration once the target is located.

return self.getTargetCopy(original.left, cloned.left, target) or \
       self.getTargetCopy(original.right, cloned.right, target)

The three statements together constitute the complete control flow of the algorithm.

Edge Cases Handled

When the original tree is empty, the initial guard returns None without attempting any further processing. This covers the scenario where both original and cloned are None.

If the target node is the root of the original tree, the value comparison succeeds on the first call, and the method returns the root of the cloned tree instantly, avoiding any unnecessary descent.

The recursion naturally accommodates trees that are highly unbalanced, such as completely left-leaning or right-leaning structures, because each call processes the corresponding child pair (original.left with cloned.left or original.right with cloned.right).

When the target node resides deep in the tree, the algorithm continues traversing until it reaches the matching depth, and the or combination ensures that once the correct cloned node is found, the remaining recursive calls unwind without further work.

Performance Optimizations

The function traverses the original and cloned trees simultaneously, eliminating the need for a separate pass to locate the target in the original tree before searching the clone. By checking the value equality at each step, it can return the cloned node as soon as the target is identified, preventing unnecessary exploration of sibling subtrees.

The use of the logical or operator provides an implicit short-circuit mechanism: once a recursive call yields a non-None node, the second call is not evaluated. This reduces the number of recursive invocations after the target has been found, saving both time and stack usage.

Because the algorithm only follows the structural path that leads to the target, it avoids visiting nodes that are unrelated to the target’s location, which is a direct consequence of the parallel traversal and early exit strategy.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have two identical sets of building blocks. One set is perfect, and the other is a copy. Someone asks you to find one specific block in the set that has been copied.

The code works just like playing a game of matching. It looks at the very first block in both sets at the exact same time. If the block in the original set is the one you are looking for, then the code knows that the matching block in the copied set is the prize you want.

If the block is not the right one, the code keeps looking deeper into the sets. It peeks at the left side of both sets to see if the target is hiding there. If it finds the target on the left, it stops and keeps that spot. If the target is not on the left, the code tries looking at the right side instead. It keeps traveling down through all the blocks until every single one has been checked or until the treasure is found.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.85 | σ = 1.30

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim JS
fpdjsns C++
fsq C++
JoshCrozier JS
Krazune C++
lkwq007 Python
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Java, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim JavaScript
fpdjsns C++
fsq C++
JoshCrozier JavaScript
Krazune C++
lkwq007 Python
varunu28 Java
YuriSpiridonov Python
27 links | 16 authors | 6 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

4 solutions   November 25, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality