↓Skip to main content
  1. LeetCode/

LeetCode 1379: Find a Corresponding Node of a Binary Tree in a Clone of That Tree

·1 min· ·
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-11-17

  • Submissions: Accepted ×3

Approach
#

The clone has the same shape, so walk both trees in lockstep (Tree Template 1). When the original reaches target (compared by identity, since values may repeat), the clone’s node at that step is the answer.

My Solution
#

class Solution:
    def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
        if not original:
            return None
        if original is target:
            return cloned
        return (self.getTargetCopy(original.left, cloned.left, target)
                or self.getTargetCopy(original.right, cloned.right, target))

Complexity
#

Time O(n), space O(h).

Mistakes to Avoid
#

  • Compare node identity with is, not values.

Interview Explanation
#

The clone has the same structure, so I recurse through both together and return the clone’s node when the original reaches the target. Time O(n).

Related

LeetCode 965: Univalued Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 965 note: every value must equal the root’s; compare values while recursing, not the booleans the recursion returns
LeetCode 993: Cousins in Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 993 note: cousins share a depth but not a parent; record x’s and y’s depth and parent during DFS and compare
LeetCode 637: Average of Levels in Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 637 note: level-order traversal, dividing each level’s sum by its count
LeetCode 404: Sum of Left Leaves
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 404 note: tell each child during DFS whether it is a left child, adding only left children that are leaves
LeetCode 226: Invert Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 226 note: swap every node’s children, using a simultaneous assignment so the already-changed side is not reused
LeetCode 111: Minimum Depth of Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 111 note: minimum depth must end at a leaf; with only one child, the empty side (depth 0) cannot count as the minimum