MediumNo. 1485LeetCode Premium
Clone Binary Tree With Random Pointer — LeetCode 1485 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Depth-First Search, Breadth-First Search, Hash Table, Binary Tree
- 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
# 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
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0653 | Two Sum IV - Input is a BST | Easy |
| 0863 | All Nodes Distance K in Binary Tree | Medium |
| 0865 | Smallest Subtree with all the Deepest Nodes | Medium |
| 0987 | Vertical Order Traversal of a Binary Tree | Hard |
| 1123 | Lowest Common Ancestor of Deepest Leaves | Medium |
| 1261 | Find Elements in a Contaminated Binary Tree | Medium |
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.