Clone Binary Tree With Random Pointer — LeetCode 1485 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchBreadth-First SearchHash TableBinary Tree
Problem
#1485
Reading time
5 min

The problem

A binary tree is given such that each node contains an additional random pointer which could point to any node in the tree or null. Return a deep copy of the tree.

Example

Input
root = [[1,null],null,[4,3],[7,0]]
Output
[[1,null],null,[4,3],[7,0]]
Explanation
The original binary tree is [1,null,4,7].

Python solution

Python
# Definition for Node.
# class Node:
#     def __init__(self, val=0, left=None, right=None, random=None):
#         self.val = val
#         self.left = left
#         self.right = right
#         self.random = random


class Solution:
    def copyRandomBinaryTree(self, root: 'Optional[Node]') -> 'Optional[NodeCopy]':
        def dfs(root):
            if root is None:
                return None
            if root in mp:
                return mp[root]
            copy = NodeCopy(root.val)
            mp[root] = copy
            copy.left = dfs(root.left)
            copy.right = dfs(root.right)
            copy.random = dfs(root.random)
            return copy

        mp = {}
        return dfs(root)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1485. Clone Binary Tree With Random Pointer is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1485. Clone Binary Tree With Random Pointer?
LeetCode 1485. Clone Binary Tree With Random Pointer is rated Medium on LeetCode.
What is the time complexity of LeetCode 1485. Clone Binary Tree With Random Pointer?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1485. Clone Binary Tree With Random Pointer?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1485. Clone Binary Tree With Random Pointer cover?
LeetCode 1485. Clone Binary Tree With Random Pointer is tagged Tree, Depth-First Search, Breadth-First Search, Hash Table and Binary Tree on LeetCode.
Is LeetCode 1485. Clone Binary Tree With Random Pointer a premium problem?
Yes. LeetCode 1485. Clone Binary Tree With Random Pointer is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview