Clone Binary Tree With Random Pointer — LeetCode 1485 Python Solution
MediumLeetCode PremiumTreeDepth-First SearchBreadth-First SearchHash TableBinary Tree
- Problem
- #1485
- Pattern
- Tree Traversal
- Reading time
- 5 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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
LeetCode 653Two Sum IV - Input is a BSTEasyLeetCode 863All Nodes Distance K in Binary TreeMediumLeetCode 865Smallest Subtree with all the Deepest NodesMediumLeetCode 987Vertical Order Traversal of a Binary TreeHardLeetCode 1123Lowest Common Ancestor of Deepest LeavesMediumLeetCode 1261Find Elements in a Contaminated Binary TreeMedium
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.